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/main
|
<file_sep>import React from "react";
import {
Card,
Button,
CardImg,
CardTitle,
CardText,
CardGroup,
CardSubtitle,
CardBody
} from "reactstrap";
class Cartao extends React.Component {
state = {
filmes: []
};
componentDidMount() {
fetch("https://apimovies.pythonanywhere.com/movies")
.then((res) => res.json())
.then((res) => {
this.setState({
filmes: res
});
});
}
render() {
return (
<div>
<h1>Lista de filmes</h1>
<ul>
{this.state.filmes.map((item) => (
<CardGroup>
<Card>
<CardImg
top
width="100%"
src="https://http2.mlstatic.com/D_NQ_NP_2X_627914-MLA40655732617_022020-V.webp"
alt="Card image cap"
/>
<CardBody>
<CardTitle tag="h6">
<b>id: </b> {item.id}
</CardTitle>
<CardTitle tag="h3">
<b>Filme: </b> {item.title}
</CardTitle>
<CardSubtitle tag="h6" className="mb-2 text-muted">
<b>Genero: </b>
{item.genre}
</CardSubtitle>
<CardText>
<b>Ano: </b>
{item.year}
</CardText>
<Button>Button</Button>
</CardBody>
</Card>
</CardGroup>
))}
</ul>
</div>
);
}
}
export default Cartao;
<file_sep>import React from "react";
import { Jumbotron, Container } from "reactstrap";
const Jumbo = (props) => {
return (
<div>
<Jumbotron fluid>
<Container fluid>
<h1 className="display-3">Eletronics.com</h1>
<p className="lead">
Tudo para game em um só lugar. Aproveite e paça já o seu xbox.
</p>
</Container>
</Jumbotron>
</div>
);
};
export default Jumbo;
<file_sep>import React from "react";
import {
Card,
Button,
CardImg,
CardTitle,
CardText,
CardGroup,
CardSubtitle,
CardBody
} from "reactstrap";
const Cartao = (props) => {
return (
<CardGroup>
<Card>
<CardImg
top
width="100%"
src="https://http2.mlstatic.com/D_NQ_NP_2X_627914-MLA40655732617_022020-V.webp"
alt="Card image cap"
/>
<CardBody>
<CardTitle tag="h5">Card title</CardTitle>
<CardSubtitle tag="h6" className="mb-2 text-muted">
Card subtitle
</CardSubtitle>
<CardText>
This is a wider card with supporting text below as a natural lead-in
to additional content. This content is a little bit longer.
</CardText>
<Button>Button</Button>
</CardBody>
</Card>
<Card>
<CardImg
top
width="100%"
src="https://http2.mlstatic.com/D_NQ_NP_2X_627914-MLA40655732617_022020-V.webp"
alt="Card image cap"
/>
<CardBody>
<CardTitle tag="h5">Card title</CardTitle>
<CardSubtitle tag="h6" className="mb-2 text-muted">
Card subtitle
</CardSubtitle>
<CardText>
This card has supporting text below as a natural lead-in to
additional content.
</CardText>
<Button>Button</Button>
</CardBody>
</Card>
<Card>
<CardImg
top
width="100%"
src="https://http2.mlstatic.com/D_NQ_NP_2X_627914-MLA40655732617_022020-V.webp"
alt="Card image cap"
/>
<CardBody>
<CardTitle tag="h5">Card title</CardTitle>
<CardSubtitle tag="h6" className="mb-2 text-muted">
Card subtitle
</CardSubtitle>
<CardText>
This is a wider card with supporting text below as a natural lead-in
to additional content. This card has even longer content than the
first to show that equal height action.
</CardText>
<Button>Button</Button>
</CardBody>
</Card>
</CardGroup>
);
};
export default Cartao;
<file_sep>import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Home from "./Home";
import Sobre from "./Sobre";
import Contato from "./Contato";
function App() {
return (
<BrowserRouter>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/sobre" component={Sobre} />
<Route path="/contato" component={Contato} />
</Switch>
</BrowserRouter>
);
}
export default App;
|
b354e9fdedace9f35d8cc03f16ec0fcbf8ecc47e
|
[
"JavaScript"
] | 4
|
JavaScript
|
rogerio1982/react_bootstrap_basic
|
ec9a7d0b958d025dfca940986871dda2a1c65210
|
d0e31b5f58033fecd517350f7633930c97dec76d
|
refs/heads/master
|
<repo_name>alchemz/TimeSeries_R<file_sep>/SimulationForACFs.r
##Q2 R code
#let e_t ~ id N(0,1), let n=100
#theta=0.25=1/4
Y.t=arima.sim(list(order=c(0,0,1),ma=0.25),n=100)
#compute the ACF
acf(Y.t)
#plot the time series
plot.ts(Y.t)
#theta=4
Y.t=arima.sim(list(order=c(0,0,1),ma=4),n=100)
#compute the ACF
acf(Y.t2)
#plot the time series
plot.ts(Y.t2)
##Q3 R code
N=50
xs1=rep(NA,N) #create a vector called xs1 of length N, filled with NAs
ys1=rep(NA,N) #create a vector called ys1 of length N, filled with NAs
xs1[1]=0 # set the first element of xs1 to zero.
#simulate xs1 using a loop
for (t in 2:N)
{
xs1[t]=xs1[t-1] + rnorm(1,0,1) # random walk for xs1
}
# simulate ys1
for (t in 1:N)
{
ys1[t]=4 + 3*t + xs1[t]
}
#compute the ACF
acf(ys1)
#compute the first 10 ACFs
acf(ys1, lag.max=10)
#plot the time series
ts.plot(ys1)
|
d3e938ab4469285bf01b7d3123ed788e10cc91a5
|
[
"R"
] | 1
|
R
|
alchemz/TimeSeries_R
|
c34ad704399c0e41216dea7a46847f3e9b84bc63
|
514b32d28ac4f944af8e0680650ec493129660cd
|
refs/heads/master
|
<file_sep>package com.zurckz.extractor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.widget.Toast;
import com.microblink.MicroblinkSDK;
import mx.openpay.android.Openpay;
import mx.openpay.android.OperationCallBack;
import mx.openpay.android.OperationResult;
import mx.openpay.android.exceptions.OpenpayServiceException;
import mx.openpay.android.exceptions.ServiceUnavailableException;
import mx.openpay.android.model.Card;
import mx.openpay.android.validation.CardValidator;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, OperationCallBack {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
public void generateToken(){
Openpay openpay = new OpenPay().getOpenpay();
Boolean isValid = true;
Card card = new Card();
card.holderName("<NAME>");
card.cardNumber("5512382364233165");
card.expirationMonth(6);
card.expirationYear(24);
card.cvv2("7431");
if (!CardValidator.validateHolderName(card.getHolderName())) {
isValid = false;
Toast.makeText(getApplicationContext(),"Name is invalid",Toast.LENGTH_LONG).show();
}
if (!CardValidator.validateCVV(card.getCvv2(),card.getCardNumber())) {
isValid = false;
Toast.makeText(getApplicationContext(),"Cvv2 is invalid",Toast.LENGTH_LONG).show();
}
if (!CardValidator.validateCard(
card.getHolderName(),
card.getCardNumber(),
Integer.parseInt(card.getExpirationMonth()),
Integer.parseInt(card.getExpirationYear()),
card.getCvv2()
)){
isValid = false;
Toast.makeText(getApplicationContext(),"Card is invalid",Toast.LENGTH_LONG).show();
}
if(isValid){
openpay.createToken(card, this);
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_tools) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void setLicense(){
MicroblinkSDK.setLicenseKey("<KEY>", this);
}
@Override
public void onError(OpenpayServiceException e) {
Toast.makeText(getApplicationContext(),"Error: "+e.getMessage(),Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),"Error Code: "+e.getErrorCode(),Toast.LENGTH_LONG).show();
}
@Override
public void onCommunicationError(ServiceUnavailableException e) {
Toast.makeText(getApplicationContext(),"C Error: "+e.getMessage(),Toast.LENGTH_LONG).show();
}
@Override
public void onSuccess(OperationResult operationResult) {
Toast.makeText(getApplicationContext(),"OK: "+operationResult.getResult().toString(),Toast.LENGTH_LONG).show();
}
}
|
f1d2dc852204447e0a80a94d6de72e56a1f859a2
|
[
"Java"
] | 1
|
Java
|
NoeCruzMW/extract-info
|
6b7dbe7c95abc6e4ceabfde7669ea7b864387ae0
|
6e7c194fdeb31b2bcf786eb8ea56e7bf4e95efdc
|
refs/heads/master
|
<repo_name>sinindra/algorithm_problem<file_sep>/codility/TapeEquilibrium.py
#!/usr/bin/python
def solution(A):
M = sum(A)
left = [0] * (len(A))
right = [0] * (len(A))
for i in range(1, len(A)):
left[i] = left[i-1] + A[i-1]
right[i] = abs(M - 2 * left[i])
return min(right[1:])
A = [3, 1, 2, 4, 3]
if __name__ == "__main__":
print(solution(A))<file_sep>/codility/MissingInteger.py
#!/usr/bin/python
def solution(A):
visit = [0] * 1000000
for num in A:
if num <= 0:
continue
else:
if visit[num-1] == 0:
visit[num-1] = 1
idx = 0
for v in visit:
if v == 0:
return idx + 1
idx += 1
return idx + 1
if __name__ == "__main__":
print(solution(A))<file_sep>/line/모의고사/1_놀이공원.py
N, K = map(int, input().split())
group = [int(input()) for _ in range(N)]
ticketBox = [0] * K
for i in range(N):
minIdx = ticketBox.index(min(ticketBox))
ticketBox[minIdx] += group[i]
print(max(ticketBox))<file_sep>/samsung/D3/6019_기차 사이의 파리.py
T = int(input())
for test_case in range(1, T + 1):
D, A, B, F = map(int, input().split())
t = D / (A + B)
dist = 0
dist = F * t
print("#{} {}".format(test_case, dist))<file_sep>/samsung/D4/5432_쇠막대기 자르기.py
T = int(input())
for test_case in range(1, T + 1):
S = list(input())
bar = 0
ans = 0
for i in range(len(S)):
if S[i] == '(' and S[i+1] == ')':
ans += bar
elif S[i] == '(':
bar += 1
elif S[i] == ')' and S[i-1] != '(':
ans += 1
bar -= 1
print("#{} {}".format(test_case, ans))
<file_sep>/samsung/모의test/2382_미생물 격리.py
from collections import defaultdict
class Virus():
def __init__(self, r, c, n, d):
self.r = r
self.c = c
self.n = n
self.d = d
self.D = [(0,0), (-1,0), (1,0), (0,-1), (0,1)]
def change(self):
if self.d == 1:
self.d = 2
elif self.d == 2:
self.d = 1
elif self.d == 3:
self.d = 4
elif self.d == 4:
self.d = 3
def move(self):
self.r, self.c = self.r + self.D[self.d][0], self.c + self.D[self.d][1]
if self.r == 0 or self.r == N-1 or self.c == 0 or self.c == N-1:
self.n = self.n // 2
self.change()
def crash(A):
global viruses
A.sort(key = lambda x:x.n, reverse=True)
while len(A) > 1:
a = A.pop()
A[0].n += a.n
viruses.remove(a)
T = int(input())
for test_case in range(1, T + 1):
N, M, K = map(int, input().split())
viruses = [Virus(*map(int, input().split())) for _ in range(K)]
for m in range(M):
grid = defaultdict(list)
for v in viruses:
v.move()
grid[(v.r, v.c)].append(v)
for g in grid.keys():
if len(grid[g]) > 1:
crash(grid[g])
ans = 0
for virus in viruses:
ans += virus.n
print("#{} {}".format(test_case, ans))<file_sep>/samsung/D3/7675_통역사 성경이.py
import re
T = int(input())
for test_case in range(1, T + 1):
N = int(input())
S = input()
S = re.split('[.?!]', S)
S_list = []
ans_list = [0] * N
for i in range(N):
S_list.append(S[i].split())
for i in range(N):
for s in S_list[i]:
if bool(re.match('^[A-Z][a-z]*',s)) and not bool(re.match('.*[0-9]+',s)) and not bool(re.match('^[A-Z].*[A-Z]+',s)):
ans_list[i] += 1
print("#{}".format(test_case), end="")
for i in range(N):
print("", ans_list[i], end="")
print()
<file_sep>/samsung/모의test/1953_탈주범 검거.py
from collections import deque
pipe_next = {0:[1, 2, 5, 6], 1:[1, 3, 6, 7], 2:[1, 2, 4, 7], 3:[1, 3, 4, 5]}
pipe = {1: [0, 1, 2, 3],
2: [0, 2],
3: [1, 3],
4: [0, 1],
5: [1, 2],
6: [2, 3],
7: [3, 0]}
direction1 = [-1, 0, 1, 0]
direction2 = [0, 1, 0, -1]
T = int(input())
for test_case in range(1, T + 1):
N, M, R, C, L = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(N)]
visit = [[0] * M for _ in range(N)]
visit[R][C] = 1
que = deque([(R, C, 1)])
ans = 0
while que:
x1, y1, t = que.popleft()
if t > L:
break
ans += 1
current_pipe = grid[x1][y1]
for i in pipe[current_pipe]:
x2, y2 = x1 + direction1[i], y1 + direction2[i]
if x2 < 0 or x2 >= N or y2 < 0 or y2 >= M:
continue
tmp_pipe = grid[x2][y2]
if tmp_pipe in pipe_next[i] and visit[x2][y2] == 0:
que.append((x2, y2, t+1))
visit[x2][y2] = 1
print("#{} {}".format(test_case, ans))<file_sep>/samsung/모의test/4013_특이한 자석.py
from collections import deque
class Gear:
def __init__(self, gear, s, direction= None, left=None, right=None):
self.gear = gear
self.left = left
self.right = right
self.s = s
self.direction = direction
self.u = self.gear[0]
self.r = self.gear[2]
self.l = self.gear[6]
def rotate(self):
self.gear.rotate(self.direction)
self.u = self.gear[0]
self.r = self.gear[2]
self.l = self.gear[6]
def score(self):
return self.u * (2 ** self.s)
T = int(input())
for test_case in range(1, T + 1):
N = int(input())
gears = [Gear(deque(list(map(int, input().split()))), i) for i in range(4)]
gears[0].right = gears[1]
gears[1].left, gears[1].right = gears[0], gears[2]
gears[2].left, gears[2].right = gears[1], gears[3]
gears[3].left = gears[2]
for i in range(N):
move = [0] * 4
visit = [0] * 4
gear_num, direction = map(int, input().split())
n = gear_num - 1
gears[n].direction = direction
que = [gears[n]]
visit[n] = 1
while que:
tmp = que.pop()
tmp_d = tmp.direction
move[tmp.s] = 1
visit[tmp.s] = 1
if tmp.right:
if tmp.r != tmp.right.l and visit[tmp.right.s] == 0:
tmp.right.direction = tmp.direction * (-1)
que.append(tmp.right)
if tmp.left:
if tmp.l != tmp.left.r and visit[tmp.left.s] == 0:
tmp.left.direction = tmp.direction * (-1)
que.append(tmp.left)
for j in range(4):
if move[j] == 1:
gears[j].rotate()
ans = sum([gears[i].score() for i in range(4)])
print("#{} {}".format(test_case, ans))
"""
기어 객체 생성.
기어 좌,우 인접 기어 링크.
기어의 위,좌,우 정보를 갖고 있고, 객체는 기어 번호와 회전 방향을 갖고 있다.
stack을 통해 기어를 돌리고, 상황에 따라 인접 기어도 회전해야 할 경우 stack에 추가.
회전이 필요한 번호를 저장하고, 모든 기어 조사가 끝나면 일괄 회전.
회전을 하면 각 정보를 업데이트.
"""
<file_sep>/samsung/D4/4530_극한의 청소 작업.py
def count(N):
if N > 0:
count = 0
N_str = str(N)[::-1]
for i in range(len(N_str)):
if int(N_str[i]) >= 4:
N_tmp = int(N_str[i]) - 1
else:
N_tmp = int(N_str[i])
if i > 0:
diff = [(10 ** j) * (9 ** (i - j - 1)) for j in range(i)]
count += N_tmp * ((10 ** i) - sum(diff))
else:
count += N_tmp
return count
T = int(input())
for test_case in range(1, T + 1):
A, B = map(int, input().split())
if A > 0 and B > 0:
ans = count(B) - count(A)
elif A < 0 and B > 0:
ans = count(B) + count(abs(A)) - 1
elif A < 0 and B < 0:
ans = count(abs(A)) - count(abs(B))
print("#{} {}".format(test_case, ans))
<file_sep>/line/모의고사/6_숫자전광판.py
def num(max_K, K, n, align):
word = [["."] * K for _ in range(2*K - 1)]
if n == 0:
word[0], word[-1] = ["#"] * K, ["#"] * K
for w in word[1:-1]:
w[0], w[-1] = "#", "#"
if n == 1:
for w in word:
w[-1] = "#"
if n == 2:
word[0], word[-1], word[K - 1] = ["#"] * K, ["#"] * K, ["#"] * K
for w in word[1:K-1]:
w[-1] = "#"
for w in word[K:-1]:
w[0] = "#"
if n == 3:
word[0], word[-1], word[K - 1] = ["#"] * K, ["#"] * K, ["#"] * K
for w in word[1:K-1]:
w[-1] = "#"
for w in word[K:-1]:
w[-1] = "#"
if n == 4:
word[K - 1] = ["#"] * K
for w in word[:K-1]:
w[0], w[-1] = "#", "#"
for w in word[K:]:
w[-1] = "#"
if n == 5:
word[0], word[-1], word[K - 1] = ["#"] * K, ["#"] * K, ["#"] * K
for w in word[1:K-1]:
w[0] = "#"
for w in word[K:-1]:
w[-1] = "#"
if n == 6:
word[-1], word[K - 1] = ["#"] * K, ["#"] * K
for w in word[:K-1]:
w[0] = "#"
for w in word[K:-1]:
w[0], w[-1] = "#", "#"
if n == 7:
word[0] = ["#"] * K
for w in word[1:]:
w[-1] = "#"
if n == 8:
word[0], word[K - 1], word[-1] = ["#"] * K, ["#"] * K, ["#"] * K
for w in word[1:K-1]:
w[0], w[-1] = "#", "#"
for w in word[K:-1]:
w[0], w[-1] = "#", "#"
if n == 9:
word[0], word[K - 1] = ["#"] * K, ["#"] * K
for w in word[1:K-1]:
w[0], w[-1] = "#", "#"
for w in word[K:]:
w[-1] = "#"
if max_K != K:
add_num = 2 * (max_K - K)
if align == "TOP":
for i in range(add_num):
word.append(["."] * K)
elif align == "BOTTOM":
tmp = [["."] * K for _ in range(add_num)]
tmp.extend(word)
word = tmp
elif align == "MIDDLE":
for i in range(int(add_num/2)):
word.append(["."] * K)
tmp = [["."] * K for _ in range(int(add_num/2))]
tmp.extend(word)
word = tmp
return word
N, align = list(map(str, input().split()))
N = int(N)
K_list, num_list = [0] * N, [0] * N
for i in range(N):
K_list[i], num_list[i] = map(str, input().split())
K_list[i] = int(K_list[i])
max_K = max(K_list)
ans = []
for i in range(N):
for j in str(num_list[i]):
ans.append(num(max_K, K_list[i], int(j), align))
for i in range(2* max_K - 1):
for j in ans:
for s in j[i]:
print(s, end="")
print("", end=" ")
print()<file_sep>/codility/GenomicRangeQuery.py
#!/usr/bin/python
def solution(S, P, Q):
ans = [0] * len(P)
for i in range(len(P)):
word = S[P[i]:Q[i] + 1]
if "A" in word:
ans[i] = 1
continue
elif "C" in word:
ans[i] = 2
continue
elif "G" in word:
ans[i] = 3
continue
elif "T" in word:
ans[i] = 4
continue
return ans
A = "ACGT"
B = []
K = []
if __name__ == "__main__":
print(solution(S, P, Q))
<file_sep>/samsung/D4/4050_재관이의 대량 할인.py
T = int(input())
for test_case in range(1, T + 1):
N = int(input())
L = list(map(int, input().split()))
L = sorted(L, reverse=True)
ans = 0
for i in range(N):
if (i + 1) % 3 == 0:
continue
else:
ans += L[i]
print("#{} {}".format(test_case, ans))<file_sep>/samsung/D4/4301_콩 많이 심기.py
T = int(input())
for test_case in range(1, T + 1):
N, M = map(int, input().split())
grid = []
ans = 0
for i in range(N):
grid.append([0] * M)
for i in range(N):
for j in range(M):
x, y = i + 2, j + 2
if grid[i][j] == 0:
if x < N:
if grid[x][j] == 0:
grid[x][j] = 1
if y < M:
if grid[i][y] == 0:
grid[i][y] = 1
for i in range(N):
for j in range(M):
if grid[i][j] == 0:
ans += 1
print("#{} {}".format(test_case, ans))<file_sep>/samsung/D4/1865_동철이의 일 분배.py
# def cal(n, S, O):
def cal(n, S):
global P, ans, arr
if S <= ans:
return
if n == N:
sol = S
if S > ans:
ans = sol
return
for i in range(N):
if not arr[i]:
if P[n][i] == 0:
continue
else:
arr[i] = 1
cal(n + 1, S * P[n][i] * 0.01)
arr[i] = 0
T = int(input())
for test_case in range(1, T + 1):
N = int(input())
P = [list(map(int, input().split())) for _ in range(N)]
print(P)
ans = 0
arr = [0] * N
for i in range(N):
arr[i] = 1
cal(1, P[0][i] * 0.01)
arr[i] = 0
print("#{} {:0.6f}".format(test_case, round(ans * 100, 6)))<file_sep>/codility/OddOccurrencesInArray.py
#!/usr/bin/python
def solution(A):
num = {}
for i in A:
if i in num:
num[i] += 1
else:
num[i] = 1
for i in list(num.keys()):
if num[i] % 2 == 1:
ans = i
return ans
A = [42]
if __name__ == "__main__":
print(solution(A))<file_sep>/line/모의고사/3_투표.py
N = int(input())
vote = [list(map(int, input().split())) for _ in range(N)]
count = [0] * 151
for S, E in vote:
for i in range(S,E):
count[i] += 1
ans = max(count)
print(ans)
<file_sep>/line/모의고사/5_보물을찾아라.py
import math
N, M = map(int, input().split())
goal = list(map(int, input().split()))
if goal[0] > N - 1 or goal[1] > M - 1:
print("fail")
elif goal == [0, 0]:
print("fail")
else:
time = sum(goal)
path = math.factorial(time) / math.factorial(goal[0]) / math.factorial(goal[1])
print(time)
print(int(path))
<file_sep>/samsung/D4/4261_빠른 휴대전화 키패드.py
key = {"2": "abc", "3": "def", "4": "ghi",
"5": "jkl", "6": "mno", "7": "pqrs",
"8": "tuv", "9": "wxyz"}
T = int(input())
for test_case in range(1, T + 1):
S, N = map(str, input().split())
word = list(map(str, input().split()))
W = []
for i in range(len(S)):
W.append(key[S[i]])
ans = 0
for i in range(int(N)):
l = 0
for j in range(len(word[i])):
if word[i][j] in key[S[j]]:
l += 1
else:
break
if l == len(S):
ans += 1
print("#{} {}".format(test_case, ans))
<file_sep>/codility/FrogRiverOne.py
#!/usr/bin/python
def solution(X, A):
leaf = [0] * X
bridge = 0
for i in range(len(A)):
if leaf[A[i]] == 0:
leaf[A[i]] = 1
bridge += 1
if bridge == X:
return i
return -1
A = (5, [1, 3, 1, 4, 2, 3, 5, 4])
if __name__ == "__main__":
print(solution(A))<file_sep>/samsung/모의test/4014_활주로 건설.py
def check(A):
d = 0
must_d = 0
down = 0
here = A[0]
for j, i in enumerate(A):
road = i
h = road - here
if h == 0:
d += 1
if down == 1:
must_d += 1
if j == len(A) - 1 and d < X:
return 0
elif h == 1: #올라갈때
if down == 1:
if must_d < 2*X:
return 0
down = 0
must_d = 0
d = 1
else:
if d < X:
return 0
d = 1
elif h == -1: #내려갈때
if down == 1:
if d < X:
return 0
must_d = 1
d = 1
else:
down = 1
must_d = 1
d = 1
if j == len(A) - 1 and X > 1:
return 0
elif abs(h) > 1:
return 0
here = road
return 1
T = int(input())
for test_case in range(1, T + 1):
N, X = map(int, input().split())
airstrip = [list(map(int, input().split())) for _ in range(N)]
for i in range(N):
tmp = [airstrip[j][i] for j in range(N)]
airstrip.append(tmp)
ans = 0
for A in airstrip:
ans += check(A)
print("#{} {}".format(test_case, ans))<file_sep>/samsung/D4/1868_파핑파핑_지뢰찾기.py
def play(i, j):
global N, grid, safe
d = [(1,-1), (1,0), (1,1), (0,-1), (0,1), (-1,-1), (-1,0), (-1,1)]
if grid[i][j] == '.':
grid[i][j] = 0
for x1, y1 in d:
x, y = i + x1, j + y1
if x < 0 or x >= N or y < 0 or y >= N or x == -1 or y == -1:
continue
if grid[x][y] == '*':
grid[i][j] += 1
def play2(i, j):
global N, grid, safe, sol
d = [(1,-1), (1,0), (1,1), (0,-1), (0,1), (-1,-1), (-1,0), (-1,1)]
que = [[i, j]]
while que:
i, j = que.pop(0)
safe.remove([i, j])
if grid[i][j] == 0:
for x1, y1 in d:
x, y = i + x1, j + y1
if x < 0 or x >= N or y < 0 or y >= N or x == -1 or y == -1:
continue
elif [x, y] in safe and [x, y] not in que:
que.append([x, y])
else:
nosafe = 1
for x1, y1 in d:
x, y = i + x1, j + y1
if x < 0 or x >= N or y < 0 or y >= N or x == -1 or y == -1:
continue
elif grid[x][y] == 0:
nosafe = 0
if nosafe:
continue
else:
for x1, y1 in d:
x, y = i + x1, j + y1
if x < 0 or x >= N or y < 0 or y >= N or x == -1 or y == -1:
continue
elif grid[x][y] == 0 and [x, y] in safe and [x, y] not in que:
que.append([x, y])
T = int(input())
for test_case in range(1, T+1):
N = int(input())
grid = []
safe = []
for i in range(N):
line = list(input())
grid.append(line)
for j in range(N):
if line[j] == '.':
safe.append([i, j])
for i, j in safe:
play(i, j)
sol = 0
while safe:
sol += 1
i, j = safe[0]
play2(i, j)
print("#{} {}".format(test_case, sol))<file_sep>/samsung/모의test/5658_보물상자 비밀번호.py
number = {"0":0, "1":1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "A":10, "B":11, "C":12, "D":13, "E":14, "F":15}
T = int(input())
for test_case in range(1, T + 1):
N, K = map(int, input().split())
nums = input()
num_list = []
span = int(N/4)
for _ in range(span):
num_list.extend([nums[i:i + span] for i in range(0, N, span)])
nums = nums[1:] + nums[0]
num_list = list(set(num_list))
num_list.sort(reverse=True)
ans = sum([(16 ** i) * number[n] for i, n in enumerate(num_list[K-1][::-1])])
print("#{} {}".format(test_case, ans))<file_sep>/line/모의고사/4_자리배정.py
N = int(input())
student = list(map(int, input().split()))
full = [i for i, s in enumerate(student) if s == 1]
if len(full) == 1:
ans = max(full[0], N - 1 - full[0])
print(ans)
else:
dist = [full[i+1] - full[i] for i in range(len(full) - 1)]
ans = int(max(dist) // 2 )
print(ans)<file_sep>/samsung/D4/3459_승자 예측하기.py
T = int(input())
for test_case in range(1, T + 1):
N = int(input())
i = 0
while N > 1:
N = int(N // 2)
i += 1
if i % 2 == 1:
ans = "Alice"
else:
ans = "Bob"
print(i, N)
print("#{} {}".format(test_case, ans))<file_sep>/codility/PermMissingElem.py
#!/usr/bin/python
def solution(A):
if len(A) == 0:
return 1
A.sort()
if A[-1] == len(A):
return len(A) + 1
for i in range(len(A)):
if i + 1 != A[i]:
return i + 1
if __name__ == "__main__":
print(solution(A))<file_sep>/samsung/D4/1861_정사각형 방.py
def move(i, j):
global grid, grid2
n = 1
d = [(0, 1), (1, 0), (0, -1), (-1, 0)]
x, y = i, j
c = True
while c:
for k in range(4):
x2, y2 = x + d[k][0], y + d[k][1]
if x2 < 0 or x2 >= N or y2 < 0 or y2 >= N:
if k == 3:
c = False
continue
if int(grid[x2][y2]) == int(grid[x][y]) + 1:
x, y = x2, y2
if grid2[x][y] != 0:
n += grid2[x][y]
c = False
break
else:
n += 1
break
elif k == 3:
c = False
grid2[i][j] = n
return
T = int(input())
for test_case in range(1, T + 1):
N = int(input())
grid = [list(input().split()) for _ in range(N)]
grid2 = [[0]*N for _ in range(N)]
for i in range(N):
for j in range(N):
move(i, j)
ans = [100000000, 0]
for i in range(N):
for j in range(N):
if grid2[i][j] > ans[1]:
ans = [int(grid[i][j]), grid2[i][j]]
elif grid2[i][j] == ans[1] and int(grid[i][j]) < ans[0]:
ans = [int(grid[i][j]), grid2[i][j]]
print("#{} {} {}".format(test_case, ans[0], ans[1]))
<file_sep>/samsung/D4/3143_가장 빠른 문자열 타이핑.py
T = int(input())
for test_case in range(1, T + 1):
a, b = map(str, input().split())
A = a.replace(b, '!')
print("#{} {}".format(test_case, len(A)))<file_sep>/codility/CyclicRotation.py
#!/usr/bin/python
def solution(A, K):
if len(A) == 0:
return A
if K == 0:
return A
if K < len(A):
ans = A[-K:] + A[:-K]
elif K % len(A) == 0:
ans = A
else:
ans = A[-(K % len(A)):] + A[:-(K % len(A))]
return ans
A = []
K = 10
if __name__ == "__main__":
print(solution(A, K))<file_sep>/line/모의고사/2_숫자카드놀이.py
from itertools import permutations
card = list(map(int, input().split()))
K = int(input())
card.sort()
perm = list(permutations(card, 3))
print("{} {} {}".format(perm[K-1][0], perm[K-1][1], perm[K-1][2]))<file_sep>/samsung/모의test/1952_수영장.py
T = int(input())
for test_case in range(1, T + 1):
prices= list(map(int, input().split()))
plan = list(map(int, input().split()))
dp = [0] * 13
for i in range(1, 13):
dp[i] = min(dp[i-1] + prices[0] * plan[i-1], dp[i-1] + prices[1])
if i >= 3:
dp[i] = min(dp[i], dp[i-3] + prices[2])
if dp[-1] > prices[-1]:
dp[-1] = prices[-1]
ans = dp[-1]
print("#{} {}".format(test_case, ans))<file_sep>/samsung/D4/7701_염라대왕의 이름 정렬.py
T = int(input())
for test_case in range(1, T + 1):
N = int(input())
nameList = {input(): 1 for _ in range(N)}
sortedName = sorted(nameList.keys(), key = lambda x : (len(x), x))
print("#{}".format(test_case))
for name in sortedName:
print(name)<file_sep>/samsung/모의test/4008_숫자 만들기.py
def dfs(i,tmp_sum):
global N, ans_max, ans_min, nums, num_op
if i == N:
if tmp_sum > ans_max:
ans_max = tmp_sum
if tmp_sum < ans_min:
ans_min = tmp_sum
return
for j in range(4):
if num_op[j] > 0:
num_op[j] -= 1
if j == 0:
tmp = tmp_sum + nums[i]
elif j == 1:
tmp = tmp_sum - nums[i]
elif j == 2:
tmp = tmp_sum * nums[i]
elif j == 3:
tmp = int(tmp_sum / nums[i])
dfs(i+1, tmp)
num_op[j] += 1
T = int(input())
for test_case in range(1, T + 1):
N =int(input())
num_op = list(map(int, input().split()))
nums = list(map(int, input().split()))
ans_max, ans_min = float('-inf'), float('inf')
dfs(1, nums[0])
ans = ans_max - ans_min
print("#{} {}".format(test_case, ans))<file_sep>/samsung/D4/3234_준환이의 양팔저울.py
def scale(left, right, n):
global bells, visit, N, ans, S, P
if left < right:
return
if n >= N:
ans += 1
return
for i in range(N):
if visit[i] == 0:
visit[i] = 1
# scale(left + [bells[i]], right, n + 1)
scale(left + bells[i], right, n + 1)
visit[i] = 0
if P[i] == 1:
visit[i] = 1
# scale(left, right + [bells[i]], n + 1)
scale(left, right + bells[i], n + 1)
visit[i] = 0
else:
continue
T = int(input())
for test_case in range(1, T + 1):
N = int(input())
bells = list(map(int, input().split()))
S = sum(bells)
visit = [0] * N
P = [0 if bells[i] * 2 > S else 1 for i in range(N)]
ans = 0
print(P)
scale(0, 0, 0)
print("#{} {}".format(test_case, ans))
def dfs(k, state, left, right):
if left < right:
return 0
if k == N :
return 1
if dp[state] != -1:
return dp[state]
sum = 0
for i in range(N):
if visit[i] == 0 :
visit[i] = 1
sum += dfs(k+1, state + mul[i], left + data[i], right)
sum += dfs(k+1, state + mul[i] * 2, left, right + data[i])
visit[i] = 0
dp[state] = sum
return sum
T = int(input())
visit= [0] * 10
mul = [1,3,9,27,81,243,729,2187,6561] # 3 ^ n 값들
for tc in range(T):
ans = 0
N = int(input())
data = list(map(int, input().split()))
dp = [-1] * 20000
ans = dfs(0, 0, 0, 0)
print("#%d %d" %(tc+1, ans))<file_sep>/samsung/D4/8659_GCD.py
def pal(s):
ans = 0
for i in range(len(s)):
for j in range(1, len(s) - i + 1):
word = s[i:i + j]
if word == word[::-1]:
ans += 1
return ans
T = int(input())
for test_case in range(1, T + 1):
s = list(input())
s_sort = sorted(s)
word = ''
for w in s_sort:
word = word + w
ans = pal(word)
print("#{} {}".format(test_case, ans))<file_sep>/samsung/D3/1215_회문1.py
import copy
def test(arr, len_str):
sol = 0
for i in range(8):
for j in range(8 - len_str + 1):
if arr[i][j:j+len_str] == arr[i][j:j+len_str][::-1]:
sol += 1
return sol
#T = int(input())
#for test_case in range(1, T+1):
for test_case in range(1, 11):
len_str = int(input())
arr = []
for i in range(8):
arr.append(list(input()))
arr_tr = copy.deepcopy(arr)
for i in range(8):
for j in range(8):
arr_tr[i][j] = arr[j][i]
sol1 = test(arr, len_str)
sol2 = test(arr_tr, len_str)
ans = sol1 + sol2
print("#{} {}".format(test_case, ans))
<file_sep>/samsung/모의test/4012_요리사.py
def dfs(F, i):
global S, ans, n, N
if len(F) == n:
s1, s2 = 0, 0
B = list(set(range(N)) - set(F))
for i in range(n - 1):
for j in range(i + 1, n):
s1 += S[F[i]][F[j]] + S[F[j]][F[i]]
s2 += S[B[i]][B[j]] + S[B[j]][B[i]]
tmp = abs(s1 - s2)
if tmp < ans:
ans = tmp
return
if i == N:
return
if len(F) < n:
dfs(F + [i], i + 1)
dfs(F, i + 1)
T = int(input())
for test_case in range(1, T + 1):
N = int(input())
n = int(N/2)
S = [ list(map(int, input().split())) for _ in range(N) ]
ans = float("inf")
dfs([], 0)
print("#{} {}".format(test_case, ans))
"""
풀이설명:
완전탐색.
DFS를 통해 재료로 들어가 순서를 하나씩 추가.
필요한 재료만큼 추가되면 리턴.
필요한 만큼 재료가 채워지면 각각 시너지를 합한다.
"""
<file_sep>/codility/MaxCounters.py
#!/usr/bin/python
def solution(N, A):
counter = [0] * N
c_max = 0
max_counter = c_max
for x in A:
if x == N + 1:
if c_max > max_counter:
counter = [c_max] * N
max_counter = c_max
else:
counter[x - 1] += 1
if counter[x - 1] > c_max:
c_max = counter[x - 1]
return counter
N, A = 5, [3, 4, 4, 6, 1, 4, 4]
if __name__ == "__main__":
print(solution(N, A))<file_sep>/samsung/D4/6109_추억의 2048게임.py
def play(d):
global N, board, visit
if d == "left":
for i in range(N):
for j in range(N):
tmp = board[i][j]
if tmp == 0:
continue
next = j - 1
while next >= 0:
if board[i][next] == 0:
if next == 0:
board[i][next] = tmp
board[i][j] = 0
break
next -= 1
continue
elif board[i][next] == tmp and visit[i][next] == 0:
board[i][next] = tmp * 2
board[i][j] = 0
visit[i][next] = 1
break
else:
board[i][j] = 0
board[i][next + 1] = tmp
break
elif d == "right":
for i in range(N):
for j in range(N)[::-1]:
tmp = board[i][j]
if tmp == 0:
continue
next = j + 1
while next < N:
if board[i][next] == 0:
if next == N - 1:
board[i][next] = tmp
board[i][j] = 0
break
next += 1
continue
elif board[i][next] == tmp and visit[i][next] == 0:
board[i][next] = tmp * 2
board[i][j] = 0
visit[i][next] = 1
break
else:
board[i][j] = 0
board[i][next - 1] = tmp
break
elif d == "up":
for i in range(N):
for j in range(N):
tmp = board[j][i]
if tmp == 0:
continue
next = j - 1
while next >= 0:
if board[next][i] == 0:
if next == 0:
board[next][i] = tmp
board[j][i] = 0
break
next -= 1
continue
elif board[next][i] == tmp and visit[next][i] == 0:
board[next][i] = tmp * 2
board[j][i] = 0
visit[next][i] = 1
break
else:
board[j][i] = 0
board[next + 1][i] = tmp
break
elif d == "down":
for i in range(N):
for j in range(N)[::-1]:
tmp = board[j][i]
if tmp == 0:
continue
next = j + 1
while next < N:
if board[next][i] == 0:
if next == N - 1:
board[next][i] = tmp
board[j][i] = 0
break
next += 1
continue
elif board[next][i] == tmp and visit[next][i] == 0:
board[next][i] = tmp * 2
board[j][i] = 0
visit[next][i] = 1
break
else:
board[j][i] = 0
board[next - 1][i] = tmp
break
T = int(input())
for test_case in range(1, T + 1):
N, d = map(str, input().split())
N = int(N)
board = [list(map(int, input().split())) for _ in range(N)]
visit = [[0] * N for _ in range(N)]
play(d)
print("#{}".format(test_case))
for i in range(N):
for j in range(N):
print(board[i][j], end=" ")
print()<file_sep>/samsung/D4/3064_binary indexed Tree.py
class BIT(object):
def __init__(self, N, nums):
self.n = N
self.nums = nums
self.tree = [0] * (N + 1)
order = 0
for i in range(self.n):
k = i + 1
while k <= self.n:
self.tree[k] += self.nums[i]
k += (k & -k)
def update(self, idx, num):
k = idx
while k <= self.n:
self.tree[k] += num
k += (k & -k)
def get(self, idx):
k = idx
sum = 0
while k > 0:
sum += self.tree[k]
k -= (k & -k)
return sum
def range_sum(self, start, end):
if start == 1:
return str(self.get(end))
else:
return str(self.get(end) - self.get(start-1))
T = int(input())
for test_case in range(1, T + 1):
N, M = map(int, input().split())
nums = list(map(int, input().split()))
B = BIT(N, nums)
ans = []
for i in range(M):
C, X, Y = map(int, input().split())
if C == 1:
B.update(X, Y)
if C == 2:
ans.append(B.range_sum(X, Y))
print("#{} {}".format(test_case, " ".join(ans)))
<file_sep>/samsung/모의test/2115_벌꿀채취.py
def pay(A):
pay = 0
for i in range(1, 1 << M):
honey = 0
tmp_pay = 0
for j in range(M):
if i & (1 << j):
honey += A[j]
tmp_pay += A[j] ** 2
if honey <= C and tmp_pay > pay:
pay = tmp_pay
return pay
T = int(input())
for test_case in range(1, T + 1):
N, M, C = map(int, input().split())
nest = [list(map(int, input().split())) for _ in range(N)]
profit = []
for i in range(N):
for j in range(N - M + 1):
profit.append(pay(nest[i][j:j+M]))
for j in range(N - M + 1, N):
profit.append(0)
ans = 0
for i in range(len(profit) - M):
for j in range(i+M, len(profit)):
ans = max(ans, profit[i] + profit[j])
print("#{} {}".format(test_case, ans))<file_sep>/codejam/Qualification Round 2019_Cryptopangrams.py
def gcd(a, b):
while b != 0:
tmp = a % b
a = b
b = tmp
return abs(a)
alpha = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
T = int(input())
for case in range(1, T + 1):
N, L = map(int, input().split())
nums = list(map(int, input().split()))
# print(len(nums))
prime = []
S = [0] * (L + 1)
que = []
for i in range(1, L):
# print(i, end=",")
# print(nums[i-1], nums[i])
tmp = gcd(nums[i-1], nums[i])
if nums[i-1] == nums[i]:
que.append(i)
continue
elif nums[i-1] % 2 == 0 and nums[i] % 2 == 0:
S[i] = 2
elif nums[i-1] % 2 != 0 and nums[i] % 2 == 0:
S[i-1] = 2
elif nums[i-1] % 2 == 0 and nums[i] % 2 != 0:
S[i+1] = 2
S[i] = tmp
# print(que)
# print(S)
while que:
idx = que.pop(0)
if S[idx + 1] != 0:
S[idx] = int(nums[idx] / S[idx + 1])
continue
elif S[idx - 1] != 0:
S[idx] = int(nums[idx - 1] / S[idx - 1])
continue
else:
que.append(idx)
S[0] = int(nums[0] / S[1])
S[-1] = int(nums[-1] / S[-2])
prime = sorted(list(set(S)))
A = {}
for i in range(26):
A[prime[i]] = alpha[i]
# print(A)
ans = ""
# print(len(S), S)
for s in S:
ans += A[s]
print("Case #{}: {}".format(case, ans))<file_sep>/samsung/모의test/5656_벽돌 깨기.py
import copy
def bid(grid, w):
for i in range(H):
if grid[i][w] == 0:
continue
else:
return (i, w)
return
def chain(grid, bid_r, bid_c, bid_s, score):
grid2 = grid
count = 0
visit = [[0] * W for _ in range(H)]
stack = [(bid_r, bid_c, bid_s)]
while stack:
r, c, s = stack.pop()
visit[r][c] = 1
grid2[r][c] = 0
count += 1
for i in range(4):
for j in range(1, s):
rr, cc = r + (j * d[i][0]), c + (j * d[i][1])
if rr < 0 or rr >= H or cc < 0 or cc >= W:
break
if visit[rr][cc] == 0 and grid2[rr][cc] != 0:
visit[rr][cc] = 1
stack.append((rr, cc, grid[rr][cc]))
for i in range(W):
for j in range(H)[::-1]:
if grid2[j][i] == 0:
for k in range(j)[::-1]:
if grid2[k][i] == 0:
continue
else:
grid2[j][i], grid2[k][i] = grid2[k][i], 0
break
return (grid2, score - count)
def dfs(n, grid, remain, o):
global ans
if n == N:
if remain < ans:
ans = remain
return
for i in range(W):
tmp_bid = bid(grid, i)
if tmp_bid:
grid2, tmp_remain = chain(copy.deepcopy(grid), tmp_bid[0], tmp_bid[1], grid[tmp_bid[0]][tmp_bid[1]], remain)
dfs(n+1, grid2, tmp_remain, o+str(i))
else:
dfs(n+1, grid, remain, o+str(i))
T = int(input())
for test_case in range(1, T + 1):
N, W, H = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(H)]
total = 0
for i in range(H):
for j in range(W):
if grid[i][j] != 0:
total += 1
d = [(0, 1), (0, -1), (1, 0), (-1, 0)]
ans = 10000
dfs(0, grid, total, "")
print("#{} {}".format(test_case, ans))<file_sep>/samsung/D4/5550_나는 개구리로소이다.py
T = int(input())
for test_case in range(1, T + 1):
sound = input()
frog = []
frog_max = 0
ans = 0
for s in sound:
if s == 'c':
frog.append(1)
if len(frog) > frog_max:
frog_max = len(frog)
elif s != 'c' and len(frog) == 0:
ans = -1
break
else:
# print(frog)
for idx in range(len(frog)):
# print(s, frog[idx])
if s == 'r' and frog[idx] == 1:
frog[idx] += 1
break
elif s == 'o' and frog[idx] == 2:
frog[idx] += 1
break
elif s == 'a' and frog[idx] == 3:
frog[idx] += 1
break
elif s == 'k' and frog[idx] == 4:
frog.pop(0)
break
elif idx == len(frog) - 1:
ans = -1
break
if ans == -1:
break
if ans == -1 or len(frog) != 0:
sol = -1
else:
sol = frog_max
print("#{} {}".format(test_case, sol))<file_sep>/codejam/Qualification Round 2019_Foregone Solution.py
T = int(input())
for test_case in range(1, T + 1):
N = input()
a, b = '', ''
for num in N:
if num == '4':
a += '2'
b += '2'
else:
a += num
b += '0'
print("Case #{}: {} {}".format(test_case, int(a), int(b)))
<file_sep>/samsung/모의test/5644_무선 충전.py
class Map():
def __init__(self, path_A, path_B, BC):
self.A = (1,1)
self.B = (10,10)
self.path_A = path_A
self.path_B = path_B
self.map = {}
for i, (x, y, c, p) in enumerate(BC):
for j in range(-c, c+1):
for k in range(-c, c+1):
if abs(j) + abs(k) <= c:
tmp = (x + j, y + k)
if tmp in self.map:
self.map[tmp].append((i, p))
else:
self.map[tmp] = [(i, p)]
self.d = [(0,0), (0, -1), (1, 0), (0, 1), (-1, 0)]
def update(self, i):
self.A = (self.A[0] + self.d[path_A[i]][0], self.A[1] + self.d[path_A[i]][1])
self.B = (self.B[0] + self.d[path_B[i]][0], self.B[1] + self.d[path_B[i]][1])
def score(self):
bc_A, bc_B = [], []
if self.A in self.map:
bc_A = self.map[self.A]
if self.B in self.map:
bc_B = self.map[self.B]
bc_A = set(bc_A)
bc_B = set(bc_B)
bc_total = bc_A | bc_B
if len(bc_total) == 0:
return 0
elif len(bc_total) == 1:
return list(bc_total)[0][1]
elif len(bc_A) + len(bc_B) == len(bc_total):
bc_A = list(bc_A)
bc_A.sort(key = lambda x:x[1])
bc_B = list(bc_B)
bc_B.sort(key = lambda x:x[1])
if len(bc_A) == 0:
return bc_B[-1][1]
if len(bc_B) == 0:
return bc_A[-1][1]
return bc_A[-1][1] + bc_B[-1][1]
else:
bc_A = list(bc_A)
bc_A.sort(key = lambda x:x[1])
bc_B = list(bc_B)
bc_B.sort(key = lambda x:x[1])
if len(bc_total) == 2:
bc_total = list(bc_total)
ans_tmp = bc_total[0][1] + bc_total[1][1]
elif bc_A[-1] == bc_B[-1]:
if len(bc_A) == 1:
ans_tmp = bc_A[-1][1] + bc_B[-2][1]
elif len(bc_B) == 1:
ans_tmp = bc_A[-2][1] + bc_B[-1][1]
else:
ans_tmp = bc_A[-1][1] + max(bc_A[-2][1], bc_B[-2][1])
else:
ans_tmp = bc_A[-1][1] + bc_B[-1][1]
return ans_tmp
def play(self, M):
ans = 0
n = 0
ans += self.score()
while n < M:
self.update(n)
ans += self.score()
n += 1
return ans
T = int(input())
for test_case in range(1, T + 1):
M, A = map(int, input().split())
path_A = list(map(int, input().split()))
path_B = list(map(int, input().split()))
BC = [tuple(map(int, input().split())) for _ in range(A)]
board = Map(path_A, path_B, BC)
ans = board.play(M)
print("#{} {}".format(test_case, ans))<file_sep>/samsung/D4/7465_창용 마을 무리의 개수.py
T = int(input())
for test_case in range(1, T + 1):
N, M = map(int, input().split())
P = [[] for _ in range(N + 1)]
for _ in range(M):
a, b = map(int, input().split())
P[a].append(b)
P[b].append(a)
visit = [True] * (N + 1)
visit[0] = False
ans = 0
for i in range(1, N + 1):
if visit[i]:
que = P[i]
while que:
tmp = que.pop(0)
if visit[tmp]:
visit[tmp] = False
que.extend(P[tmp])
ans += 1
print("#{} {}".format(test_case, ans))
<file_sep>/samsung/D5/5953_수의 새로운 비교 기준.py
def nsum(s, N):
ans = 0
if len(s) != N:
s = "0" * (N-len(s)) + s
for i in s:
ans += int(i)
return ans
def prod(s, N):
ans = 1
if len(s) != N:
s = "0" * (N-len(s)) + s
for i in s:
ans *= int(i) + 1
return ans
def nint(s, N):
ans = 0
if len(s) != N:
s = "0" * (N-len(s)) + s
for i in s:
N -= 1
ans += int(i) * (10 ** N)
return ans
T = int(input())
for test_case in range(1, T+1):
s = input()
N = len(s)
sol = {}
for i in range(10 ** N):
i = str(i)
sol[i] = (nsum(i,N), prod(i,N), nint(i,N))
sol = sorted(sol.items(), key = (lambda x: x[1]))
print(sol)
<file_sep>/codility/BinaryGap.py
#!/usr/bin/python
def solution(N):
b = str(format(N, 'b'))
tmp, ans = 0, 0
for i in b:
if i == "0":
tmp += 1
elif i == "1":
if tmp > ans:
ans = tmp
tmp = 0
print(i, ans, tmp)
return b + " : " + str(ans)
N = 21564864
if __name__ == "__main__":
print(solution(N))<file_sep>/codility/FrogJmp.py
#!/usr/bin/python
def solution(X, Y, D):
if X == Y:
return 0
delta = Y - X
if D >= delta:
return 1
elif D == 1:
return delta
elif delta % D == 0:
return int(delta / D)
else:
return int(delta // D) + 1
if __name__ == "__main__":
print(solution(X, Y ,D))<file_sep>/codejam/Qualification Round 2019_You can go your own way.py
T = int(input())
for case in range(1, T + 1):
N = int(input())
path = input()
new_path = ''
for p in path:
if p == 'S':
new_path += 'E'
else:
new_path += 'S'
print("Case #{} {}".format(case, new_path))<file_sep>/samsung/D4/6959_이상한 나라의 덧셈게임.py
T = int(input())
for test_case in range(1, T + 1):
N = input()
count = 0
if len(N) == 1:
count = 0
else:
while len(N) >= 2:
N = str(int(N[0]) + int(N[1])) + N[2:]
count += 1
if count % 2 == 0:
ans = "B"
else:
ans = "A"
print("#{} {}".format(test_case, ans))
<file_sep>/codility/CountDiv.py
#!/usr/bin/python
def solution(A, B, K):
mb = int(B // K)
ma = int(A // K)
if A % K == 0:
ans = mb - ma + 1
else:
ans = mb - ma
return ans
A = 1
B = 2
K = 3
if __name__ == "__main__":
print(solution(A, B, K))
<file_sep>/samsung/모의test/2477_차량 정비소.py
class Customer(object):
def __init__(self, i, t, start=None, end=None, A=None, B=None):
self.i = i
self.t = t
self.start = start
self.end = end
self.A = A
self.B = B
T = int(input())
for test_case in range(1, T + 1):
N, M, K, A, B = map(int, input().split())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))
customers = list(map(int, input().split()))
wait_rec = [Customer(i+1, t) for i, t in enumerate(customers)]
print(wait_rec)
wait_rep = []
fin = []
rec, rep = [0] * N, [0] * M
t = 0
while len(fin) < K:
for i in range(N):
if rec[i] == 0 and wait_rec:
if t >= wait_rec[0].t:
C = wait_rec.pop(0)
C.start, C.end, C.A = t, t+As[i], i+1
rec[i] = C
elif rec[i] != 0:
C = rec[i]
print(C.end)
if t >= C.end:
C.start, C.end = None, None
wait_rep.append(C)
rec[i] = 0
if wait_rec:
if t >= wait_rec[0].t:
C = wait_rec.pop(0)
C.start, C.end, C.A = t, t+As[i], i+1
print(C.start, C.end)
rec[i] = C
print("rec", t, wait_rec, rec)
if wait_rep or rep != [0] * M:
for j in range(M):
if rep[j] == 0:
if wait_rep:
C = wait_rep.pop(0)
C.start, C.end, C.B = t, t+Bs[j], j+1
print(C.start, C.end)
rep[j] = C
else:
C = rep[j]
if t >= C.end:
fin.append(C)
rep[j] = 0
if wait_rep:
C = wait_rep.pop(0)
C.start, C.end, C.B = t, t+Bs[j], j+1
rep[j] = C
print("rep", t, wait_rep, rep)
print(fin)
t += 1
input()
ans = 0
for k in fin:
if k.A == A and k.B == B:
ans += k.i
if ans == 0:
ans = -1
print("#{} {}".format(test_case, ans))<file_sep>/samsung/D4/4366_정식이의 은행업무.py
def search():
global p_A, p_B, n_A, n_B
for i in p_A:
for j in p_B:
if n_A + i == n_B +j:
ans = n_A + i
return ans
T = int(input())
for test_case in range(1, T + 1):
A = input()
B = input()
n_A = int(A, 2)
n_B = int(B, 3)
p_A = []
p_B = []
idx = 0
for i in A[::-1]:
if i == "1":
p_A.append(-1 * 2 ** idx)
if i == "0":
p_A.append(2 ** idx)
idx += 1
p_A.append(2 ** idx)
idx = 0
for i in B[::-1]:
if i == "0":
p_B.append(3 ** idx)
p_B.append(2 * 3 ** idx)
if i == "1":
p_B.append(-1 * 3 ** idx)
p_B.append(3 ** idx)
if i == "2":
p_B.append(-1 * 3 ** idx)
p_B.append(-2 * 3 ** idx)
idx += 1
p_B.extend([3 ** idx, 2 * 3 ** idx])
ans = search()
print("#{} {}".format(test_case, ans))
|
6ec015d11b7626ebc2f74eef44dc58524e1315a1
|
[
"Python"
] | 55
|
Python
|
sinindra/algorithm_problem
|
a34770ae64eaaff3f98072c924649314458e25ae
|
caa82e8379f93b617ba73673ca2023321f3dcf91
|
refs/heads/master
|
<repo_name>develersrl/gatt<file_sep>/linux/device.go
package linux
import (
"errors"
"fmt"
"log"
"sync"
"syscall"
"unsafe"
"github.com/develersrl/gatt/linux/gioctl"
"github.com/develersrl/gatt/linux/socket"
)
type device struct {
fd int
dev int
name string
rmu *sync.Mutex
wmu *sync.Mutex
}
func newDevice(n int, chk bool) (*device, error) {
fmt.Printf("LA MARZOCCO - socket.Socket(socket.AF_BLUETOOTH, syscall.SOCK_RAW, socket.BTPROTO_HCI)\n")
fd, err := socket.Socket(socket.AF_BLUETOOTH, syscall.SOCK_RAW, socket.BTPROTO_HCI)
fmt.Printf("LA MARZOCCO - fd=%v, err=%v\n", fd, err)
if err != nil {
return nil, err
}
if n != -1 {
return newSocket(fd, n, chk)
}
req := devListRequest{devNum: hciMaxDevices}
fmt.Printf("LA MARZOCCO - gioctl.Ioctl(uintptr(fd)=%v, hciGetDeviceList, uintptr(unsafe.Pointer(&req)))\n", uintptr(fd))
err = gioctl.Ioctl(uintptr(fd), hciGetDeviceList, uintptr(unsafe.Pointer(&req)))
fmt.Printf("LA MARZOCCO - err=%v\n", err)
if err != nil {
return nil, err
}
fmt.Printf("LA MARZOCCO - int(req.devNum)=%v\n", int(req.devNum))
for i := 0; i < int(req.devNum); i++ {
d, err := newSocket(fd, i, chk)
if err == nil {
log.Printf("dev: %s opened", d.name)
return d, err
}
}
return nil, errors.New("no supported devices available")
}
func newSocket(fd, n int, chk bool) (*device, error) {
i := hciDevInfo{id: uint16(n)}
fmt.Printf("LA MARZOCCO - gioctl.Ioctl(uintptr(fd)=%v, hciGetDeviceInfo, uintptr(unsafe.Pointer(&i)))\n", uintptr(fd))
err := gioctl.Ioctl(uintptr(fd), hciGetDeviceInfo, uintptr(unsafe.Pointer(&i)))
fmt.Printf("LA MARZOCCO - err=%v\n", err)
if err != nil {
return nil, err
}
name := string(i.name[:])
// Check the feature list returned feature list.
if chk && i.features[4]&0x40 == 0 {
err := errors.New("does not support LE")
log.Printf("dev: %s %s", name, err)
return nil, err
}
log.Printf("dev: %s up", name)
fmt.Printf("LA MARZOCCO - gioctl.Ioctl(uintptr(fd)=%v, hciUpDevice, uintptr(n)=%v)\n", uintptr(fd), uintptr(n))
err = gioctl.Ioctl(uintptr(fd), hciUpDevice, uintptr(n))
fmt.Printf("LA MARZOCCO - err=%v\n", err)
if err != nil {
if err != syscall.EALREADY {
return nil, err
}
log.Printf("dev: %s reset", name)
fmt.Printf("LA MARZOCCO - gioctl.Ioctl(uintptr(fd)=%v, hciResetDevice, uintptr(n)=%v)\n", uintptr(fd), uintptr(n))
err = gioctl.Ioctl(uintptr(fd), hciResetDevice, uintptr(n))
fmt.Printf("LA MARZOCCO - err=%v\n", err)
if err != nil {
return nil, err
}
}
log.Printf("dev: %s down", name)
fmt.Printf("LA MARZOCCO - gioctl.Ioctl(uintptr(fd)=%v, hciDownDevice, uintptr(n)=%v)\n", uintptr(fd), uintptr(n))
err = gioctl.Ioctl(uintptr(fd), hciDownDevice, uintptr(n))
fmt.Printf("LA MARZOCCO - err=%v\n", err)
if err != nil {
return nil, err
}
// Attempt to use the linux 3.14 feature, if this fails with EINVAL fall back to raw access
// on older kernels.
sa := socket.SockaddrHCI{Dev: n, Channel: socket.HCI_CHANNEL_USER}
fmt.Printf("sa := socket.SockaddrHCI{Dev: %v, Channel: socket.HCI_CHANNEL_USER}", n)
fmt.Printf("LA MARZOCCO - socket.Bind(fd=%v, &sa)\n", fd)
err = socket.Bind(fd, &sa)
fmt.Printf("LA MARZOCCO - err=%v\n", err)
if err != nil {
if err != syscall.EINVAL {
return nil, err
}
log.Printf("dev: %s can't bind to hci user channel, err: %s.", name, err)
sa := socket.SockaddrHCI{Dev: n, Channel: socket.HCI_CHANNEL_RAW}
fmt.Printf("sa := socket.SockaddrHCI{Dev: %v, Channel: socket.HCI_CHANNEL_RAW}", n)
fmt.Printf("LA MARZOCCO - socket.Bind(fd=%v, &sa)\n", fd)
err = socket.Bind(fd, &sa)
fmt.Printf("LA MARZOCCO - err=%v\n", err)
if err != nil {
log.Printf("dev: %s can't bind to hci raw channel, err: %s.", name, err)
return nil, err
}
}
return &device{
fd: fd,
dev: n,
name: name,
rmu: &sync.Mutex{},
wmu: &sync.Mutex{},
}, nil
}
func (d device) Read(b []byte) (int, error) {
d.rmu.Lock()
defer d.rmu.Unlock()
fmt.Printf("syscall.Read(d.fd=%v, b=%v)\n", d.fd, b)
n, err := syscall.Read(d.fd, b)
fmt.Printf("n=%v err=%v\n", n, err)
return n, err
}
func (d device) Write(b []byte) (int, error) {
d.wmu.Lock()
defer d.wmu.Unlock()
fmt.Printf("syscall.Write(d.fd=%v, b=%v)\n", d.fd, b)
n, err := syscall.Write(d.fd, b)
fmt.Printf("n=%v err=%v\n", n, err)
return n, err
}
func (d device) Close() error {
fmt.Printf("syscall.Close(d.fd=%v)\n", d.fd)
err := syscall.Close(d.fd)
fmt.Printf("err=%v\n", err)
return err
}
<file_sep>/go.mod
module github.com/develersrl/gatt
go 1.13
|
c9611a83fe98b533c7979c540d80ad39e0ce23d5
|
[
"Go Module",
"Go"
] | 2
|
Go
|
develersrl/gatt
|
27a6e456c692058c041a8ea7cf89c76adc5a845f
|
7678a5d6b93d87a62f35346fcf8984d2884a7287
|
refs/heads/master
|
<repo_name>ntuzer/BackToTheFuture<file_sep>/lib/flux_capacitor.rb
require 'date'
require 'byebug'
class BackToTheFuture
attr_reader :previous_date, :current_date
def initialize
@previous_date = nil
@current_date = nil
get_dates
end
def time_travel(num = nil) #write to file
flux_capacitor(num) unless @current_date.saturday?
save_date
get_dates
end
def flux_capacitor(num)
return if @current_date.saturday?
puts '----------------------------------------------------------'
time = 0
num = Random.rand(10) + 5 if num.nil?
puts "Today, #{@current_date.to_s}, we will commit #{num} times"
puts '----------------------------------------------------------'
num.times do
date = set_travel_date(time)
time += 1
fluxing(date)
message = 'Create commits for graph'
system("git add .")
sleep 0.1
system("git commit -m \"#{message}\"")
sleep 0.1
system("GIT_COMMITTER_DATE=\"#{date}\" git commit --amend --no-edit --date \"#{date}\"")
sleep 0.1
end
# system("git push origin master")
end
def push
system("git push origin master")
end
private
def set_travel_date(time = 0)
# 2017-10-15 20:19:19 -0700
time = time < 10 ? "0#{time}" : time.to_s
"#{@current_date.to_s} 20:#{time}:05 -0700"
end
def fluxing(plutonium)
delorean = File.open('logs/data.txt','w')
delorean.puts(plutonium)
delorean.close
end
def load_date
date = File.readlines('logs/captains_log.txt')[0].chomp
year = date[0..3].to_i
mon = date[5..6].to_i
day = date[8..9].to_i
Date.new(year, mon, day)
end
def save_date
file = File.open('logs/captains_log.txt','w')
file.puts(@current_date)
file.close
end
def get_dates
@previous_date = load_date
@current_date = @previous_date.next_day
end
end
if $PROGRAM_NAME == __FILE__
delorean = BackToTheFuture.new
puts "-------------------------------------------------------------"
puts "How many days would you like to travel?"
num = gets.chomp.to_i
puts "Your input: #{num}"
puts 'Enter number of commits:'
commits = gets.chomp
commits = commits.empty? ? nil : commits.to_i
start_date = delorean.previous_date
puts "-------------------------------------------------------------"
puts "Fluxing..."
num.times do
puts "Traveling to #{start_date + num}"
delorean.time_travel(commits)
end
puts "-------------------------------------------------------------"
puts "Pushing to Master"
puts "-------------------------------------------------------------"
delorean.push
puts "-------------------------------------------------------------"
puts "Thank you!"
puts "-------------------------------------------------------------"
end
|
ed41cb534a3e48c5ea9089963370c4b77ac98a22
|
[
"Ruby"
] | 1
|
Ruby
|
ntuzer/BackToTheFuture
|
67ce1a9e004c05b456b481ac06fd8c707cc67fa8
|
31005955db27518c3e4e542e73661f6f9e8b8b6e
|
refs/heads/master
|
<repo_name>kunalkhade/Wheeled-Robots<file_sep>/Problem Number - 1.py
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.pyplot as plt
import math
#Sampling Rate
N = 50
#Time intervals
t0 = 0.0
t1 = 5.0
t2 = 6.0
t3 = 10.0
#Sample Points
ta = np.linspace(t0, t1, N)
tb = np.linspace(t1, t2, N)
tc = np.linspace(t2, t3, N)
dta = (t1-t0)/N
dtb = (t2-t1)/N
dtc = (t3-t2)/N
#Create an empty array in order to store values
xp1 = np.ones((N))
yp1 = np.ones((N))
th1 = np.ones((N))
xp2 = np.ones((N))
yp2 = np.ones((N))
th2 = np.ones((N))
xp3 = np.ones((N))
yp3 = np.ones((N))
th3 = np.ones((N))
#Robot Parameters r = radius L = Distance between two wheels
r = 5.0
L = 16.0
#Wheel Speed
w11 = [2]*N
w12 = [2]*N
w21 = [3]*N
w22 = [4]*N
w31 = [1]*N
w32 = [2]*N
#Initial values
xp1[0] = 0.0
yp1[0] = 0.0
th1[0] = 0.0
#
for i in range(N-1):
xp1[i+1] = xp1[i] + (r*dta/2.0)*(w11[i] + w12[i])*math.cos(th1[i])
yp1[i+1] = yp1[i] + (r*dta/2.0)*(w11[i] + w12[i])*math.sin(th1[i])
th1[i+1] = th1[i] + (r*dta/(2.0*L))*(w11[i] - w12[i])
xp2[0] = xp1[N-1]
yp2[0] = yp1[N-1]
th2[0] = th1[N-1]
for i in range(N-1):
xp2[i+1] = xp2[i] + (r*dtb/2.0)*(w21[i] + w22[i])*math.cos(th2[i])
yp2[i+1] = yp2[i] + (r*dtb/2.0)*(w21[i] + w22[i])*math.sin(th2[i])
th2[i+1] = th2[i] + (r*dtb/(2.0*L))*(w21[i] - w22[i])
xp3[0] = xp2[N-1]
yp3[0] = yp2[N-1]
th3[0] = th2[N-1]
for i in range(N-1):
xp3[i+1] = xp3[i] + (r*dtc/2.0)*(w31[i] + w32[i])*math.cos(th3[i])
yp3[i+1] = yp3[i] + (r*dtc/2.0)*(w31[i] + w32[i])*math.sin(th3[i])
th3[i+1] = th3[i] + (r*dtc/(2.0*L))*(w31[i] - w32[i])
#Add all points into one
xx = np.concatenate((xp1, xp2, xp3), axis=None)
yy = np.concatenate((yp1, yp2, yp3), axis=None)
#Plot all the points
plt.xlabel(' X- Axis ')
plt.ylabel(' Y- Axis ')
plt.title(' Path of The Robot ')
plt.plot(xx,yy, 'ro')
plt.plot(xp3[N-1],yp3[N-1], 'bo')
plt.show()<file_sep>/Problem Number - 4.py
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.pyplot as plt
import math
#Robot Parameters
r = 2.0
l = 5.0
dt = 2
Tend = 1800.0
#Sampling Rate
N = int(Tend/dt)
v = 1.0
k1 = 2.0
k2 = 0.2
#points to be reach
xend = [0, 100, 200, 300, 400, 500, 400,300, 200, 100, 0, 0]
yend = [0, 100, 0, -100, 0, 100, 200, 300, 300, 200, 100, 0] #all points are in meters
#Blank Array
x = np.zeros(N)
y = np.zeros(N)
th = np.zeros(N)
A = np.zeros(N)
B = np.zeros(N)
C = np.zeros(N)
k = 3
i = 0
for k in range(12):
if k == 1:
while(i<N-1): #gradual increase included
th_err = math.atan2(yend[k] - y[i], xend[k] - x[i]) - th[i] #orientation error
d1 = abs(x[i] - xend[k])
d2 = abs(y[i] - yend[k])
w = v
d = math.sqrt(d1*d1+d2*d2) #linear dist
if (d<0.2): break
w1 = (w + k1*th_err)
w2 = (w - k1*th_err)
if (d<10):
w1, w2 = k2*d*(w + k1*th_err), k2*d*(w - k1*th_err)
dx = (r*dt/2.0)*(w1+w2)*math.cos(th[i])
dy = (r*dt/2.0)*(w1+w2)*math.sin(th[i])
dth = (r*dt/(2.0*l))*(w1-w2)
x[i+1] = x[i] + dx
y[i+1] = y[i] + dy
th[i+1] = th[i] + dth
i = i+1
elif k == 12: #gradual decrease included
while(i<N-1):
th_err = math.atan2(yend[k] - y[i], xend[k] - x[i]) - th[i] #orientation error
d1 = abs(x[i] - xend[k])
d2 = abs(y[i] - yend[k])
w = v
d = math.sqrt(d1*d1+d2*d2) #linear dist
if (d<0.2): break
w1 = k2*d*(w + k1*th_err)
w2 = k2*d*(w - k1*th_err)
dx = (r*dt/2.0)*(w1+w2)*math.cos(th[i])
dy = (r*dt/2.0)*(w1+w2)*math.sin(th[i])
dth = (r*dt/(2.0*l))*(w1-w2)
x[i+1] = x[i] + dx
y[i+1] = y[i] + dy
th[i+1] = th[i] + dth
i = i+1
else: #constant speed
while(i<N-1):
th_err = math.atan2(yend[k] - y[i], xend[k] - x[i]) - th[i] #orientation error
d1 = abs(x[i] - xend[k])
d2 = abs(y[i] - yend[k])
w = v
d = math.sqrt(d1*d1+d2*d2) #linear dist
if (d<0.2): break
w1 = w + k1*th_err
w2 = w - k1*th_err
if (d<10):
w1, w2 = k2*d*(w + k1*th_err), k2*d*(w - k1*th_err)
dx = (r*dt/2.0)*(w1+w2)*math.cos(th[i])
dy = (r*dt/2.0)*(w1+w2)*math.sin(th[i])
dth = (r*dt/(2.0*l))*(w1-w2)
x[i+1] = x[i] + dx
y[i+1] = y[i] + dy
th[i+1] = th[i] + dth
i = i+1
#Plot the path
plt.xlabel(' X- Axis ')
plt.ylabel(' Y- Axis ')
plt.title(' Path of The Robot ')
plt.plot(x,y, 'ro')
plt.show()
<file_sep>/Problem Number - 2.py
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.pyplot as plt
import math
#Sampling Rate
N = 200
t0 = 0.0
t1 = 10.0
#Time Interval
t = np.linspace(t0, t1, N)
dt = (t1-t0)/N
xp = np.ones((N))
yp = np.ones((N))
th = np.ones((N))
#Robot Parameters
r = 0.08
L1 = 0.30
L2 = 0.20
#Create an empty array in order to store values
xp[0] = 0.0
yp[0] = 0.0
th[0] = 0.0
for i in range(N-1):
ph1 = 0.75*np.cos(i/30)
ph2 = 1.5*np.cos(i/30)
ph3 = -1.0
ph4 = 0.5
A = (ph1 + ph2 + ph3 + ph4)
B = (-ph1 + ph2 + ph3 - ph4)
C = (-ph1 + ph2 - ph3 + ph4)
xp[i+1] = xp[i] + (r*dt/4.0)*(A* np.cos(th[i])- B*np.sin(th[i]))
yp[i+1] = yp[i] + (r*dt/4.0)*(A* np.sin(th[i]) + B*np.cos(th[i]))
th[i+1] = th[i] + (r*dt/(4.0))*((1/(L1-L2)*C))
plt.scatter(xp, yp, color='g')
plt.xlabel(' X Direction ')
plt.ylabel(' Y Direction ')
plt.title(' Mechanum Wheel Drive Path ')
plt.pause(0.03)
#Plot all the points
u = 8 * np.cos(th[i])
v = 8 * np.sin(th[i])
print (xp[N-1], yp[N-1], u, v)
plt.quiver(xp[N-1],yp[N-1],u,v)
plt.savefig('mecanumpath.pdf')
plt.show()
plt.xlabel(' X Direction ')
plt.ylabel(' Y Direction ')
plt.title(' Mechanum Wheel Drive Path ')
plt.xlim(0,0.25)
plt.ylim(-0.3,0.05)
plt.quiver(xp[N-1],yp[N-1],u,v)
plt.plot(xp,yp, 'bo')
plt.show()<file_sep>/README.md
# Wheeled-Robots
Robotics Programs -Differential Drive Robot, Mecanum Drive robot
Problem No – 1
Given a differential drive robot starting from (0,0,0) find the final position when wheel velocities are
given by:
t=0 to t=5: 𝜔1 = 2, 𝜔2 = 2
t=5 to t=6: 𝜔1 = 3, 𝜔2 = 4
t=6 to t=10: 𝜔1 = 1, 𝜔
Solution –
Full Problem Solution – The problem statement is divided into three different time slots (t0-t1, t1-t2, t2- t3). So there are three different problem statements and solved one by one. Each time slot is divided into 50 different points and sampled them. Nine blank arrays assigned (xp1,2,3 yp1,2,3 th1,2,3) which stores position and orientation information of differential drive robot. Six different wheel speeds assign in order to get the movement of the robot mentioned in the problem statement. In three different ‘for’ loops made in order to get three arrays which have information about the robot’s movement. Combine three strings and plot using matplot library (path of the robot fig.1).

Problem No - 2
Assume that you have a rectangular Mechanum robot with L1=0.30m, L2=0.20m and r=0.08 Find the path of the robot for the given wheel rotations: ϕ˙1=0.75∗cos(t/3.0), ϕ˙2=1.5∗cos(t/3.0), ϕ˙3=−1.0, ϕ˙4=0.5. Start with x,y,θ=0 and set t=0, Δt=0.05. Run the simulation for 200 iterations (or for 10 seconds). Keeping the x and y locations in an array is an easy way to generate a plot of the robot’s path. If x, y are arrays of x-y locations then try
Showing the orientation takes a bit more work. Matplotlib provides a vector plotting method. You need to hand it the location of the vector and the vector to be plotted, (x,y,u,v), where (x,y) s the vector location and (u,v) are the x and y components of the vector. You can extract those from θ using u=s∗cos(θ) and v=s∗sin(θ) where ss is a scale factor (to give a good length for the image, e.g. 0.075). The vector plot commands are then
Solution –
In the solution 200 points generated using linspace command which is equally spaced between 0to10 time frame. Blank array for Xp, Yp and Th generated in order to store the location of the mechanum wheel robot. Parameter of the robot is already provided in the problem statement. A B and C are the vehicle equation used from the textbook which is used to generate state co-ordinates of the robot. The array of x,y, and th parameters generate and store into the above blank arrays. Plot the points with the help of matplotlib library. The quiver function is used from matplotlib in order to generate the orientation of the robot and plot. Display all the plotted points using show command.

Problem No - 3
Real motion and measurement involves error and this problem will introduce the concepts. Assume that you have a differential drive robot with wheels that are 20cm in radius and L is 12cm. Using the differential drive code (forward kinematics) from the text, develop code to simulate the robot motion when the wheel velocities are ϕ˙1=0.25t2, ϕ˙2=0.5t. The starting location is [0,0] with θ=0.
Plot the path of the robot on 0≤t≤. It should end up somewhere near [50,60].
Solution –
In the solution equal 100 points generated from 0 to 5. Dotphi1 and dotphi2 velocities are provided in order to compute the robot motion. Blank array Xp Yp and Th are made in order to store x y and th coordinates. Using for loop co-ordinates will be generated and store into blank arrays. Plot and show all the coordinates using matplotlib commands.

Problem Number - 4
Using python, drive the DD robot along the following points at uniform speed with a p-controller: (0,0), (1,1), (2,0), (3,-1), (4,0), (5,1), (4,2), (3,3), (2, 3), (1,2), (0,1), (0,0). Ramp up at the first point and ramp down to stop at the last point. Assume the units for the previous points are in meters. The DD robot will have L = 5cm and R = 2cm, and be a 10cm diameter robot. Plot the points and the robot’s path. Note: you don’t have to slow down for the interior points on the list. Use the 10cm diameter as the switching distance.
Solution –
In this problem proportional controller is used in order to correct the error between current position of robot and desired positions (xend, yend). There are 2 controlled parameters that variable which are orientation and velocity. In this case I considered a constant velocity and change in orientation as a error. Depending on the error proportionally gain added into the system and try to correct orientation. In the beginning robot uses minimum speed to ramp up. And at the end it decreases its speed in order to get smooth motion between the complete journey (Ref Appendix problem no1 code). Program is developed on the basis of 1800 msec which is linearly sample. Matplot library used to generate plot.

<file_sep>/Problem Number - 3 (Solution-1).py
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.pyplot as plt
import math
#Sampling Rate
N = 100
t0 = 0.0
t1 = 5.0
#Time Interval
t = np.linspace(t0, t1, N)
dt = (t1-t0)/N
one = np.ones((N))
xp = np.ones((N))
yp = np.ones((N))
th = np.ones((N))
#Robot Parameters
r = 20.0
L = 12.0
dotphi1 = 0.25*t*t
dotphi2 = 0.5*t
#Create an empty array in order to store values
xp[0] = 0.0
yp[0] = 0.0
th[0] = 0.0
for i in range(N-1):
xp[i+1] = xp[i] + (r*dt/2.0)*(dotphi1[i] + dotphi2[i])*math.cos(th[i])
yp[i+1] = yp[i] + (r*dt/2.0)*(dotphi1[i] + dotphi2[i])*math.sin(th[i])
th[i+1] = th[i] + (r*dt/(2.0*L))*(dotphi1[i] - dotphi2[i])
#Plot all the points
plt.xlabel(' X Direction ')
plt.ylabel(' Y Direction ')
plt.title(' DD Wheel Drive Path ')
plt.xlim(-20,100)
plt.ylim(-20,70)
plt.plot(xp,yp, 'bo')
plt.show()
|
15875034d68202926e5bcc71f96823d1af3fe998
|
[
"Markdown",
"Python"
] | 5
|
Python
|
kunalkhade/Wheeled-Robots
|
835a7d80f220c2e9e245695528eae0c174e78da6
|
8df8cd534c99e37a7b407a661f5ff6c6621f8c11
|
refs/heads/master
|
<file_sep>bundle update
bundle install
rails g scaffold report caption:string body:text token:string
bundle exec rake db:create
<file_sep>class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :reports
before_create :create_token
def create_token
token = Digest::SHA1.hexdigest("#{id}#{rand.to_s}")[0..15]
write_attribute(:token, token)
end
end
<file_sep># abst-abst
## bootstrap
[Rin](https://github.com/raryosu/Rin)
<file_sep>class Report < ActiveRecord::Base
belongs_to :user
before_create :create_token
def create_token
token = Digest::SHA1.hexdigest("#{id}#{rand.to_s}")[0..15]
write_attribute(:token, token)
end
end
<file_sep>source 'https://rubygems.org'
gem 'rails', '4.2.6'
gem 'coffee-rails', '~> 4.1.0'
gem 'devise'
gem 'gem_sort'
gem 'jbuilder', '~> 2.0'
gem 'jquery-rails'
gem 'mysql2', '~> 0.3.18'
gem 'pry'
gem 'sass', '~> 3.4.19'
gem 'sass-rails', '~> 5.0'
gem 'scss_lint', '~> 0.47.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'turbolinks'
gem 'uglifier', '>= 1.3.0'
gem 'win32console' if RUBY_PLATFORM =~ /win32/i || RUBY_PLATFORM =~ /mingw32/i
gem 'windows-pr' if RUBY_PLATFORM =~ /win32/i || RUBY_PLATFORM =~ /mingw32/i
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> in views
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'web-console', '~> 2.0'
end
<file_sep>json.extract! report, :id, :caption, :body, :token, :created_at, :updated_at
json.url report_url(report, format: :json)<file_sep>Rails.application.routes.draw do
devise_for :users
# resources :reporters, only: [:show]
resources :reports
# resources :reports, shallow: do
# resources :valuations, only: [:new, :create]
# end
root 'reports#index'
end
|
52d7a643c3c716c079540afe7b24721c2917b479
|
[
"Markdown",
"Ruby"
] | 7
|
Markdown
|
Okusan818/abst-abst
|
1800cd71f9222ecd95747309ede8f34aee1430e8
|
fef56b93ac5e748a2678b4394a70839194dd94c7
|
refs/heads/master
|
<repo_name>ichigosyrup11/slide-pdf.js<file_sep>/lib/pdf-controller.js
/**
* Created by azu on 2014/09/27.
* LICENSE : MIT
*/
"use strict";
var domify = require("domify");
var domMap = require("./dom-map").domMap;
// load custom event polyfill
require("custom-event-polyfill");
function PDFController(container) {
this.pdfDoc = null;
this.pageNum = 1;
this.promiseQueue = Promise.resolve();
this.pdfContainer = container;
var html = require("fs").readFileSync(__filename + ".hbs", "utf-8");
var dom = domify(html);
/*
* @type {Object.<string, Node>}
*/
var mapping = {
progressBar: ".slide-progress-bar",
canvas: ".pdf-canvas",
textLayer: ".pdf-textLayer",
annotationLayer: ".pdf-annotationLayer",
loading: ".pdf-loading"
};
this.domMapObject = domMap(dom, mapping);
container.appendChild(dom);
this.canvasContext = this.domMapObject.canvas.getContext('2d');
this.fitItSize();
}
var prop = PDFController.prototype;
prop.events = {
"before_pdf_rendering": "before-pdf-rendering",
"after_pdf_rendering": "after_pdf_rendering"
};
prop.loadDocument = function (url) {
var that = this;
// load complete
function hideLoadingIcon() {
that.domMapObject.loading.style.display = "none"
}
that.pdfContainer.addEventListener(that.events.before_pdf_rendering, hideLoadingIcon);
return PDFJS.getDocument(url).then(function (pdfDoc_) {
that.pdfDoc = pdfDoc_;
return that.queueRenderPage(that.pageNum);
}).then(function () {
that.pdfContainer.removeEventListener(that.events.before_pdf_rendering, hideLoadingIcon);
});
};
prop.queueRenderPage = function (pageNum) {
var that = this;
if (that.pdfDoc == null) {
return this.promiseQueue;
}
this.promiseQueue = this.promiseQueue.then(function () {
return that.renderPage(pageNum);
});
return this.promiseQueue;
};
prop.fitItSize = function () {
var that = this;
return new Promise(function (resolve) {
var containerRect = that.pdfContainer.getBoundingClientRect();
that.domMapObject.canvas.width = containerRect.width;
that.domMapObject.canvas.height = containerRect.height;
resolve(containerRect);
}).then(function () {
return that.queueRenderPage(that.pageNum);
});
};
prop.cleanup = function () {
var range = document.createRange();
var domMapObject = this.domMapObject;
range.selectNodeContents(domMapObject.textLayer);
range.deleteContents();
range.selectNodeContents(domMapObject.annotationLayer);
range.deleteContents();
};
prop.renderPage = function renderPage(pageNum) {
var that = this;
var beforeEvent = new CustomEvent(this.events.before_pdf_rendering, {
detail: this
});
this.pdfContainer.dispatchEvent(beforeEvent);
// Using promise to fetch the page
return that.pdfDoc.getPage(pageNum).then(function (page) {
that.cleanup();
var domMapObject = that.domMapObject;
var viewport = page.getViewport(domMapObject.canvas.width / page.getViewport(1.0).width);
domMapObject.canvas.height = viewport.height;
domMapObject.canvas.width = viewport.width;
domMapObject.textLayer.style.width = domMapObject.canvas.style.width;
domMapObject.textLayer.style.height = domMapObject.canvas.style.height;
// Render PDF page into canvas context
var renderContext = {
canvasContext: that.canvasContext,
viewport: viewport
};
var renderPromise = page.render(renderContext).promise;
var textLayerPromise = page.getTextContent().then(function (textContent) {
var textLayerBuilder = new TextLayerBuilder({
textLayerDiv: domMapObject.textLayer,
viewport: viewport,
pageIndex: 0
});
textLayerBuilder.setTextContent(textContent);
});
return Promise.all([renderPromise, textLayerPromise]).then(function (result) {
setupAnnotations(page, viewport, domMapObject.annotationLayer);
});
}).then(function () {
that.updateProgress(pageNum);
var afterEvent = new CustomEvent(that.events.after_pdf_rendering, {
detail: this
});
that.pdfContainer.dispatchEvent(afterEvent);
});
};
prop.prevPage = function prevPage() {
if (this.pageNum <= 1) {
return;
}
this.pageNum--;
return this.queueRenderPage(this.pageNum);
};
prop.nextPage = function onNextPage() {
if (this.pageNum >= this.pdfDoc.numPages) {
return;
}
this.pageNum++;
return this.queueRenderPage(this.pageNum);
};
prop.updateProgress = function updateProgress(pageNum) {
var progressBar = this.domMapObject.progressBar;
if (progressBar !== null) {
var numSlides = this.pdfDoc.numPages;
var position = pageNum - 1;
var percent = (numSlides === 1) ? 100 : 100 * position / (numSlides - 1);
progressBar.style.width = percent.toString() + '%';
}
};
function setupAnnotations(page, viewport, annotationArea) {
return page.getAnnotations().then(function (annotationsData) {
viewport = viewport.clone({
dontFlip: true
});
for (var i = 0; i < annotationsData.length; i++) {
var data = annotationsData[i];
if (!data || !data.hasHtml) {
continue;
}
var element = PDFJS.AnnotationUtils.getHtmlElement(data);
var rect = data.rect;
var view = page.view;
rect = PDFJS.Util.normalizeRect([
rect[0],
view[3] - rect[1] + view[1],
rect[2],
view[3] - rect[3] + view[1]
]);
element.style.left = (rect[0]) + 'px';
element.style.top = (rect[1]) + 'px';
element.style.position = 'absolute';
var transform = viewport.transform;
var transformStr = 'matrix(' + transform.join(',') + ')';
CustomStyle.setProp('transform', element, transformStr);
var transformOriginStr = -rect[0] + 'px ' + -rect[1] + 'px';
CustomStyle.setProp('transformOrigin', element, transformOriginStr);
if (data.subtype === 'Link' && !data.url) {
// In this example, we do not handle the `Link` annotation without url.
// If you want to handle these links, see `web/page_view.js`.
continue;
}
console.log(element);
annotationArea.appendChild(element);
}
});
}
module.exports = PDFController;
|
545a2719e18dde8513c5a60d7e793474e9269c21
|
[
"JavaScript"
] | 1
|
JavaScript
|
ichigosyrup11/slide-pdf.js
|
47ede518a5eb58d581d5715ff05f8a86bcfd12f2
|
642343b00e9b6eaa94909baeea113ff95af90aa8
|
refs/heads/master
|
<file_sep>package it.polito.tdp.poweroutages.model;
import java.time.*;
public class PowerOutages implements Comparable<PowerOutages>{
private int id;
private int custumersAffected;
private LocalDateTime dateEventBegan;
private LocalDateTime dateEventFinished;
private Nerc nerc;
private int demandLoss;
public PowerOutages(int id, int custumersAffected, LocalDateTime dateEventBegan, LocalDateTime dateEventFinished, Nerc nerc, int demandLoss) {
super();
this.id = id;
this.custumersAffected = custumersAffected;
this.dateEventBegan = dateEventBegan;
this.dateEventFinished = dateEventFinished;
this.nerc=nerc;
this.demandLoss = demandLoss;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCustumersAffected() {
return custumersAffected;
}
public void setCustumersAffected(int custumersAffected) {
this.custumersAffected = custumersAffected;
}
public LocalDateTime getDateEventBegan() {
return dateEventBegan;
}
public void setDateEventBegan(LocalDateTime dateEventBegan) {
this.dateEventBegan = dateEventBegan;
}
public LocalDateTime getDateEventFinished() {
return dateEventFinished;
}
public void setDateEventFinished(LocalDateTime dateEventFinished) {
this.dateEventFinished = dateEventFinished;
}
public Nerc getNerc() {
return nerc;
}
public void setNerc(Nerc nerc) {
this.nerc = nerc;
}
public int getDemandLoss() {
return demandLoss;
}
public void setDemandLoss(int demandLoss) {
this.demandLoss = demandLoss;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PowerOutages other = (PowerOutages) obj;
if (id != other.id)
return false;
return true;
}
public long getOre() {
return Duration.between(this.dateEventBegan,this.dateEventFinished).toHours();
}
@Override
public int compareTo(PowerOutages po) {
// TODO Auto-generated method stub
return (int) dateEventBegan.compareTo(po.dateEventBegan);
}
public String toString() {
//return ""+" -- Began: "+this.dateEventBegan+" -- Finished: "+this.dateEventFinished+" -- Hours: "+this.getOre()+" -- Custumers affected: "+this.custumersAffected;
return String.format("Began: %s ; Finished: %s ; Hours: %3d ; Custumers affected: %7d ",
dateEventBegan,dateEventFinished,getOre(),custumersAffected );
}
}
<file_sep>package it.polito.tdp.poweroutages.model;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class TestModel {
public static void main(String[] args) {
Model model = new Model();
System.out.println(model.getNercList());
PowerOutages po = new PowerOutages(1, 10000, LocalDateTime.of(2013, 02, 15, 18, 30), LocalDateTime.of(2013, 02, 17, 20, 50), null, 0);
long ore = Duration.between( po.getDateEventBegan(),po.getDateEventFinished()).toHours();
System.out.print((int)ore);
}
}
<file_sep>package it.polito.tdp.poweroutages.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import it.polito.tdp.poweroutages.model.Nerc;
import it.polito.tdp.poweroutages.model.PowerOutages;
public class PowerOutageDAO {
public List<Nerc> getNercList() {
String sql = "SELECT id, value FROM nerc";
List<Nerc> nercList = new ArrayList<>();
try {
Connection conn = ConnectDB.getConnection();
PreparedStatement st = conn.prepareStatement(sql);
ResultSet res = st.executeQuery();
while (res.next()) {
Nerc n = new Nerc(res.getInt("id"), res.getString("value"));
nercList.add(n);
}
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return nercList;
}
public List<PowerOutages> getBlackoutsIntervallo(Nerc nerc, int i, int j) {
String sql = "SELECT id, customers_affected, date_event_began, date_event_finished, demand_loss " +
"FROM poweroutages p " +
"WHERE YEAR(p.date_event_began)>= ? AND YEAR(p.date_event_began)<= ? AND p.nerc_id= ?";
List<PowerOutages> nercList = new ArrayList<PowerOutages>();
try {
Connection conn = ConnectDB.getConnection();
PreparedStatement st = conn.prepareStatement(sql);
st.setInt(1, i);
st.setInt(2, j);
st.setInt(3, nerc.getId());
ResultSet res = st.executeQuery();
while (res.next()) {
PowerOutages po = new PowerOutages(res.getInt("id"), res.getInt("customers_affected"),
(res.getTimestamp("date_event_began")).toLocalDateTime(), (res.getTimestamp("date_event_finished")).toLocalDateTime(), nerc, res.getInt("demand_loss"));
nercList.add(po);
}
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return nercList;
}
}
|
86ca01122fe43f6c09f74b4c9f6dcd8fd0f468e1
|
[
"Java"
] | 3
|
Java
|
CampanioloNF/Lab07
|
7935434b005a02f9ccd5fecae6f21332160f1578
|
1529ec05d14a2e9619441159df6b040231ed5292
|
refs/heads/master
|
<repo_name>iunki/petrushenko_JBjava<file_sep>/mm-app/mm-service/src/main/java/ru/kpfu/itis/MyServiceImpl.java
package ru.kpfu.itis;
public class MyServiceImpl implements MyService{
private MyModel model = new MyModel();
@Override
public String getMyModelValue() {
model.setValue("Hello, world!");
return model.getValue();
}
}
<file_sep>/SocialNetwork/src/main/java/ru/kpfu/itis/repository/TweetRepository.java
package ru.kpfu.itis.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import ru.kpfu.itis.model.Tweet;
import ru.kpfu.itis.model.User;
import java.util.List;
@Repository
public interface TweetRepository extends CrudRepository<Tweet, Long> {
public List<Tweet> findByUserOrderByDateDesc(User user);
}
<file_sep>/StudentsScore/src/main/java/ru/kpfu/itis/controller/MainController.java
package ru.kpfu.itis.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import ru.kpfu.itis.model.Score;
import ru.kpfu.itis.model.Student;
import ru.kpfu.itis.model.enums.Subject;
import ru.kpfu.itis.repository.StudentRepository;
import ru.kpfu.itis.service.ScoreService;
@Controller
public class MainController {
@Autowired
ScoreService scoreService;
@Autowired
StudentRepository studentRepository;
@RequestMapping(value = "/")
public String getIndexPage() {
return "index";
}
@RequestMapping(value = "/average", method = RequestMethod.POST)
public String getAveragePage(@RequestParam(value = "firstname") String firstname, @RequestParam(value = "surname") String surname, @RequestParam(value = "lastname") String lastname, Model model) {
Student student = studentRepository.getByName(firstname, surname, lastname);
model.addAttribute("average", scoreService.getAvg(student));
return "average";
}
@RequestMapping(value = "/sum", method = RequestMethod.POST)
public String getSummPage(@RequestParam(value = "firstname") String firstname, @RequestParam(value = "surname") String surname, @RequestParam(value = "lastname") String lastname, Model model) {
Student student = studentRepository.getByName(firstname, surname, lastname);
model.addAttribute("sum", scoreService.getSum(student));
return "sum";
}
@RequestMapping(value = "/score", method = RequestMethod.POST)
public String getScorePage(@RequestParam(value = "firstname") String firstname, @RequestParam(value = "surname") String surname, @RequestParam(value = "lastname") String lastname, @RequestParam(value = "subject") Integer subject, Model model) {
Student student = studentRepository.getByName(firstname, surname, lastname);
model.addAttribute("score", scoreService.getScore(student, subject));
return "score";
}
}
<file_sep>/mm-app/build.gradle
group 'multimodule'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'war'
sourceCompatibility = 1.5
repositories {
mavenCentral()
}
dependencies {
compile (
'org.springframework:spring-webmvc:4.1.5.RELEASE',
'org.slf4j:slf4j-api:1.7.10'
)
providedCompile(
'javax.servlet:javax.servlet-api:3.1.0',
)
runtime(
'log4j:log4j:1.2.17',
'org.slf4j:jcl-over-slf4j:1.7.10',
'org.slf4j:slf4j-log4j12:1.7.10'
)
testCompile(
'junit:junit:4.12',
'org.springframework:spring-test:4.1.5.RELEASE'
)
compile project(":mm-service")
compile project(":mm-model")
}
<file_sep>/StudentsScore/src/main/webapp/resources/database.properties
jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://localhost:5432/MyBase
jdbc.username=postgres
jdbc.password=<PASSWORD><file_sep>/AOP/src/main/java/ru/kpfu/itis/aop/ServiceAspect.java
package ru.kpfu.itis.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import java.util.Arrays;
import java.util.Date;
public class ServiceAspect {
public void before() {
System.out.println("");
}
public Object timeLog(ProceedingJoinPoint joinPoint) throws Throwable {
Date start = new Date(System.currentTimeMillis());
System.out.println("Start invoking "
+ joinPoint.getTarget().getClass().getSimpleName()
+ "."
+ joinPoint.getSignature().getName()
+ " with params "
+ Arrays.toString(joinPoint.getArgs())
+ "\n start: " + start);
Object result = joinPoint.proceed();
Date end = new Date(System.currentTimeMillis());
System.out.println("end: " + end + "\n duration: " + (end.getTime() - start.getTime()) + " ms");
return result;
}
public Object excLog(ProceedingJoinPoint joinPoint) {
try {
Object obj = joinPoint.proceed();
return obj;
} catch (Throwable throwable) {
System.out.println("[Exception]: " + throwable.toString() + "in" + joinPoint.getSignature().getName() + " catched for arguments: " + Arrays.toString(joinPoint.getArgs()));
return null;
}
}
}
<file_sep>/Task10/src/Main.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws Throwable {
Class clazz = Class.forName("Task10");
Object obj = clazz.newInstance();
Method[] methods = clazz.getMethods();
System.out.println(Arrays.toString(methods));
methods[1].invoke(obj, 10);
methods[0].invoke(obj);
}
}
<file_sep>/MedClinic/src/main/java/ru/kpfu/itis/model/JurInfo.java
package ru.kpfu.itis.model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.UUID;
@Entity
@Table(name = "jur_info")
public class JurInfo {
public JurInfo() {
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
@Column(name = "series")
private String series;
@Column(name = "number")
private String number;
@Column(name = "unic_number_uuid", columnDefinition = "UUID", nullable = false)
private UUID uuid;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getSeries() {
return series;
}
public void setSeries(String series) {
this.series = series;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public UUID getUuid() {
return uuid;
}
public void setUuid(UUID uuid) {
this.uuid = uuid;
}
}
<file_sep>/MedClinic/src/main/java/ru/kpfu/itis/repository/StuffDataRepository.java
package ru.kpfu.itis.repository;
import java.math.BigDecimal;
import java.sql.Date;
/**
* Created by Þëèÿ on 04.11.2015.
*/
public interface StuffDataRepository {
BigDecimal findAvgSalaryByMedClinic(String name);
public Integer getSalaryOfStuff(String medClinicName, String fio);
public Date getStartDate(String medClinicName, String fio);
public Date getEndDate(String medClinicName, String fio);
}
<file_sep>/SocialNetwork/src/main/java/ru/kpfu/itis/service/UserService.java
package ru.kpfu.itis.service;
import org.springframework.stereotype.Service;
import ru.kpfu.itis.form.UserRegistrationForm;
import ru.kpfu.itis.model.User;
@Service
public interface UserService {
void saveNewUser(UserRegistrationForm form);
User findOneByUsername(String username);
void securedMethod();
User getCurrentUser();
}
<file_sep>/AOP/src/main/java/ru/kpfu/itis/controller/IndexController.java
package ru.kpfu.itis.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.kpfu.itis.service.UserService;
@Controller
public class IndexController {
@Autowired
UserService userService;
@RequestMapping(value = "/")
public String getIndexPage() {
return "index";
}
}
<file_sep>/mm-app/mm-service/src/main/java/ru/kpfu/itis/MyService.java
package ru.kpfu.itis;
public interface MyService {
public String getMyModelValue();
}
<file_sep>/StudentsScore/src/main/java/ru/kpfu/itis/repository/ScoreRepository.java
package ru.kpfu.itis.repository;
import ru.kpfu.itis.model.Score;
import ru.kpfu.itis.model.enums.Subject;
import java.math.BigDecimal;
import java.math.BigInteger;
public interface ScoreRepository {
public BigInteger getSum(Integer id);
public BigDecimal getAvg(Integer id);
public Integer getScore(Integer id, Subject subject);
public void addScore(Score score);
}
<file_sep>/mm-app/src/main/java/ru/kpfu/itis/webapp/controller/MyController.java
package ru.kpfu.itis.webapp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.kpfu.itis.MyService;
import ru.kpfu.itis.MyServiceImpl;
@Controller
public class MyController {
MyService myService = new MyServiceImpl();
@RequestMapping("/")
public String getIndexPage(Model model) {
model.addAttribute("text", myService.getMyModelValue());
return "index";
}
}
<file_sep>/AOP/src/main/java/ru/kpfu/itis/service/UserService.java
package ru.kpfu.itis.service;
import org.springframework.stereotype.Service;
import ru.kpfu.itis.form.UserRegistrationForm;
@Service
public interface UserService {
void saveNewUser(UserRegistrationForm form);
void securedMethod();
}
<file_sep>/SocialNetwork/src/main/java/ru/kpfu/itis/service/TweetService.java
package ru.kpfu.itis.service;
import ru.kpfu.itis.model.Tweet;
import ru.kpfu.itis.model.User;
import java.util.List;
public interface TweetService {
void addTweet(User user, String text);
public List<Tweet> getTweets(User user);
}
<file_sep>/mm-app/settings.gradle
rootProject.name = 'mm-app'
include 'mm-model'
include 'mm-service'
<file_sep>/MedClinic/src/main/java/ru/kpfu/itis/repository/MedClinicRepository.java
package ru.kpfu.itis.repository;
import java.util.List;
/**
* Created by Þëèÿ on 04.11.2015.
*/
public interface MedClinicRepository {
public String getProfitableClinic();
public List<String> getMedClinics();
}
<file_sep>/SocialNetwork/src/main/java/ru/kpfu/itis/util/UserRegistrationValidator.java
package ru.kpfu.itis.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import ru.kpfu.itis.form.UserRegistrationForm;
import ru.kpfu.itis.model.User;
import ru.kpfu.itis.repository.UserRepository;
@Component
public class UserRegistrationValidator implements Validator {
@Autowired
UserRepository userRepository;
@Override
public boolean supports(Class<?> aClass) {
return aClass.equals(User.class);
}
@Override
public void validate(Object o, Errors errors) {
UserRegistrationForm form = (UserRegistrationForm)o;
if (userRepository.findByUsername(form.getUsername().toLowerCase()) != null) {
errors.rejectValue("username", "", "This username is not avaliable");
}
}
}
<file_sep>/SocialNetwork/src/main/java/ru/kpfu/itis/controller/AuthController.java
package ru.kpfu.itis.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.kpfu.itis.form.UserRegistrationForm;
import ru.kpfu.itis.model.User;
import ru.kpfu.itis.service.UserService;
import ru.kpfu.itis.util.UserRegistrationValidator;
import javax.validation.Valid;
@Controller
public class AuthController {
@Autowired
UserService userService;
@Autowired
UserRegistrationValidator validator;
@RequestMapping(value = "/")
public String getIndexPage(){
return "index";
}
@RequestMapping(value = "/login")
public String getLoginPage(@RequestParam(value = "error", required = false) Boolean error, Model model) {
if (Boolean.TRUE.equals(error)) {
model.addAttribute("error", error);
}
return "login";
}
@RequestMapping(value = "/registration", method = RequestMethod.GET)
public String getRegistrationPage(Model model) {
model.addAttribute("userform", new UserRegistrationForm());
return "registration";
}
@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registerUser(@ModelAttribute("userform") @Valid UserRegistrationForm form, BindingResult result) {
validator.validate(form, result);
if (result.hasErrors()) {
return "registration";
}
userService.saveNewUser(form);
return "redirect:/login";
}
@RequestMapping(value = "/users/{username}")
public String showUserPage(@PathVariable("username") String username, Model model) {
model.addAttribute("currUsername", username);
model.addAttribute("notAnonymous", SecurityContextHolder.getContext().getAuthentication().isAuthenticated()+"");
User user = userService.findOneByUsername(username);
model.addAttribute("firstname", user.getFirstname());
model.addAttribute("surname", user.getSurname());
model.addAttribute("lastname", user.getLastname());
model.addAttribute("city", user.getCity());
model.addAttribute("bDay", user.getbDay());
return "user-page";
}
@RequestMapping(value = "/users")
public String users (){
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = user.getUsername();
return "redirect:/users/"+username;
}
}
|
3cd201546c0c1b94eedc5298b1c2e4534abd9f36
|
[
"Java",
"INI",
"Gradle"
] | 20
|
Java
|
iunki/petrushenko_JBjava
|
e61f329cfc37e5c7faf27323bb81a5a906e54f02
|
abc65f9e1bd435d4f82478d0828084b7a4bc102a
|
refs/heads/main
|
<file_sep>import time
import sys
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.setwarnings(False)
while (1):
GPIO.output(11, GPIO.HIGH)
GPIO.output(13, GPIO.HIGH)
GPIO.output(15, GPIO.HIGH)
time.sleep(1)
GPIO.output(11, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
GPIO.output(15, GPIO.LOW)
time.sleep(1)
<file_sep># CO-LAB
Run the script to install an requirements for the programs to run. <br>
Issues? Email Me: <EMAIL>
</br>
Week 8:
Week 9:

Week 10:
https://www.raspberrypi-spy.co.uk/2018/04/i2c-oled-display-module-with-raspberry-pi/
https://github.com/adafruit/Adafruit_CircuitPython_SSD1306.git
<file_sep>import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.output(11, GPIO.HIGH)
buzzStatus = 1
def swLed(ev=None):
global buzzStatus
buzzStatus = not buzzStatus
GPIO.output(11, buzzStatus)
if buzzStatus == 1:
print('Switch status: OFF')
else:
print('Switch status: ON')
try:
GPIO.add_event_detect(12, GPIO.FALLING, callback=swLed, bouncetime=200)
while 1:
time.sleep(0.1)
except KeyboardInterrupt:
GPIO.output(11, GPIO.HIGH)
print("Done")
GPIO.cleanup()
<file_sep>import time
import sys
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.setwarnings(False)
N=int(input("Enter the number of times: "))
while (N):
GPIO.output(11, GPIO.HIGH)
GPIO.output(13, GPIO.HIGH)
GPIO.output(15, GPIO.HIGH)
time.sleep(1)
GPIO.output(11, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
GPIO.output(15, GPIO.LOW)
time.sleep(1)
N-=1
<file_sep>import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(33, GPIO.OUT) #Output
GPIO.setup(35, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Input 1
GPIO.setup(37, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Input 2
try:
while(1):
a,b = GPIO.input(35),GPIO.input(37)
c = a or b
if c:
GPIO.output(33, GPIO.HIGH)
else:
GPIO.output(33, GPIO.LOW)
except KeyboardInterrupt:
GPIO.output(33, GPIO.HIGH)
try:
while(1):
a,b = GPIO.input(35),GPIO.input(37)
c = a or b
if c:
GPIO.output(33, GPIO.HIGH)
else:
GPIO.output(33, GPIO.LOW)
except KeyboardInterrupt:
GPIO.output(33, GPIO.HIGH)
<file_sep>import time
import sys
import RPi.GPIO as GPIO
import itertools
def bin_led(b4,b3,b2,b1):
if b4:
GPIO.output(31, GPIO.HIGH)
else:
GPIO.output(31, GPIO.LOW)
if b3:
GPIO.output(33, GPIO.HIGH)
else:
GPIO.output(33, GPIO.LOW)
if b2:
GPIO.output(35, GPIO.HIGH)
else:
GPIO.output(35, GPIO.LOW)
if b1:
GPIO.output(37, GPIO.HIGH)
else:
GPIO.output(37, GPIO.LOW)
time.sleep(1)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(31, GPIO.OUT)
GPIO.setup(33, GPIO.OUT)
GPIO.setup(35, GPIO.OUT)
GPIO.setup(37, GPIO.OUT)
GPIO.setwarnings(False)
print("Ring Counter")
count = 0
b1,b2,b3,b4 = 0,0,0,1
while (1):
b1,b2,b3,b4 = b4,b1,b2,b3
print(b1,b2,b3,b4)
if ((b1,b2,b3,b4)==(1,0,0,0)):
count+=1
if count==3:
break
bin_led(b1,b2,b3,b4)
bin_led(0,0,0,0)
time.sleep(0.01)
bin_led(1,1,1,1)
time.sleep(0.01)
bin_led(0,0,0,0)
time.sleep(0.01)
bin_led(1,1,1,1)
time.sleep(0.01)
print("Twisted Ring counter")
b1,b2,b3,b4 = 0,0,0,0
while ((b1,b2,b3,b4)!=(0,0,0,1)):
b1,b2,b3,b4 = 1-b4,b1,b2,b3
print(b1,b2,b3,b4)
bin_led(b1,b2,b3,b4)
GPIO.output(37, GPIO.LOW)
GPIO.output(35, GPIO.LOW)
GPIO.output(33, GPIO.LOW)
GPIO.output(31, GPIO.LOW)
<file_sep>sudo apt install -y python3-dev
sudo apt install -y python-smbus i2c-tools
sudo apt install -y python3-pil
sudo apt install -y python3-pip
sudo apt install -y python3-setuptools
sudo apt install -y python3-rpi.gpio
sudo apt install -y python-dev
sudo apt install -y python-smbus i2c-tools
sudo apt install -y python-pil
sudo apt install -y python-pip
sudo apt install -y python-setuptools
i2cdetect -y 1
i2cdetect -y 0
sudo apt install -y git
git clone https://github.com/adafruit/Adafruit_Python_SSD1306.git
cd Adafruit_Python_SSD1306
sudo python3 setup.py install
cd examples
python3 shapes.py
<file_sep>import board
import digitalio
from PIL import Image, ImageDraw, ImageFont
import adafruit_ssd1306
# Setting some variables for our reset pin etc.
RESET_PIN = digitalio.DigitalInOut(board.D4)
# Very important... This lets py-gaugette 'know' what pins to use in order to reset the display
i2c = board.I2C()
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C, reset=RESET_PIN)
# Clear display.
oled.fill(0)
oled.show()
# Create blank image for drawing.
image = Image.new("1", (oled.width, oled.height))
draw = ImageDraw.Draw(image)
text = input("Enter the text: ")
w, h = input("Enter the position w,h with max (128,64): ").split(",")
w,h = int(w),int(h)
# Draw the text
draw.text((w,h), text, fill=255)
# Display image
oled.image(image)
oled.show()
<file_sep>import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.output(11, GPIO.HIGH)
ledStatus = 1
def swLed(ev=None):
global ledStatus
ledStatus = not ledStatus
GPIO.output(11, ledStatus)
if ledStatus == 1:
print('Switch status: OFF','Led OFF')
else:
print('Switch status: ON','Led ON')
try:
GPIO.add_event_detect(12, GPIO.FALLING, callback=swLed, bouncetime=200)
while 1:
time.sleep(0.1)
except KeyboardInterrupt:
GPIO.output(11, GPIO.HIGH)
print("Done")
GPIO.cleanup()
<file_sep>import time
import sys
import RPi.GPIO as GPIO
import itertools
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.setwarnings(False)
N=int(input("Enter the number of times: "))
while N:
GPIO.output(11, GPIO.HIGH)
time.sleep(0.2)
GPIO.output(11,GPIO.LOW)
N-=1
<file_sep>import RPi.GPIO as GPIO
import time
import board
import digitalio
from PIL import Image, ImageDraw, ImageFont
import adafruit_ssd1306
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.output(11, GPIO.HIGH)
ledStatus = 1
RESET_PIN = digitalio.DigitalInOut(board.D4)
# Very important... This lets py-gaugette 'know' what pins to use in order to reset the display
i2c = board.I2C()
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C, reset=RESET_PIN)
# Clear display.
oled.fill(0)
oled.show()
# Create blank image for drawing.
image = Image.new("1", (oled.width, oled.height))
draw = ImageDraw.Draw(image)
def swLed(ev=None):
global ledStatus
ledStatus = not ledStatus
GPIO.output(11, ledStatus)
if ledStatus == 1:
print('Switch status: OFF','Led OFF')
draw.text((0, 0), "Switch status: OFF", font=font, fill=255)
oled.image(image)
oled.show()
else:
print('Switch status: ON','Led ON')
draw.text((0, 0), "Switch status: ON", font=font, fill=255)
oled.image(image)
oled.show()
try:
GPIO.add_event_detect(12, GPIO.FALLING, callback=swLed, bouncetime=200)
while 1:
time.sleep(0.1)
except KeyboardInterrupt:
GPIO.output(11, GPIO.HIGH)
print("Done")
GPIO.cleanup() <file_sep>import time
import sys
import RPi.GPIO as GPIO
def bin_led(b1,b2,b3):
if b3:
GPIO.output(11, GPIO.HIGH)
else:
GPIO.output(11, GPIO.LOW)
if b2:
GPIO.output(13, GPIO.HIGH)
else:
GPIO.output(13, GPIO.LOW)
if b1:
GPIO.output(15, GPIO.HIGH)
else:
GPIO.output(15, GPIO.LOW)
time.sleep(1)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.setwarnings(False)
print("Binary counter")
for i in itertools.product([0,1],repeat=3):
b1,b2,b3 = i
bin_led(b1,b2,b3)
print("Binary counter done, Now\n")
print("Ring counter")
N=8
<file_sep>import sys
import board
import digitalio
from PIL import Image
import adafruit_ssd1306
# Setting some variables for our reset pin etc.
RESET_PIN = digitalio.DigitalInOut(board.D4)
i2c = board.I2C()
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C, reset=RESET_PIN)
# Clear display.
oled.fill(0)
oled.show()
# Open, resize, and convert image to Black and White
try:
image = (
Image.open(sys.argv[1])
.resize((oled.width, oled.height), Image.BICUBIC)
.convert("1")
)
# Display the converted image
oled.image(image)
oled.show()
except KeyboardInterrupt:
oled.fill(0)
oled.show()
|
4a78a29286ddc8c4db5072faec7871eadc6bc812
|
[
"Markdown",
"Python",
"Shell"
] | 13
|
Python
|
JithLord/CO-LAB
|
d9805e8bbd4815c1dc9ab6a581d838c88a50b35a
|
411ba42e03760f22f24ed10e411f7552a11b5905
|
refs/heads/master
|
<file_sep>package com.tracker.student.student99.models;
import io.realm.RealmObject;
public class FeeDetails extends RealmObject{
private String feeDetails;
private float amount;
private float total;
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
private String section;
public float getTotal() {
return total;
}
public void setTotal(float total) {
this.total = total;
}
public String getFeeDetails() {
return feeDetails;
}
public void setFeeDetails(String feeDetails) {
this.feeDetails = feeDetails;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
}
<file_sep>package com.tracker.student.student99.activities;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.tracker.student.student99.R;
import com.tracker.student.student99.adapters.PaymentsAdapter;
import com.tracker.student.student99.appconstants.KeyConstants;
import com.tracker.student.student99.models.FeeDetails;
import com.tracker.student.student99.models.Payments;
import com.tracker.student.student99.models.Student;
import java.security.Key;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmResults;
public class PayMentDetailsActivity extends Activity {
Realm realm;
float totalFee;
float paidAmount;
TextView totalFeeVew;
TextView paidId;
Button payBtnId;
Student currentStudent;
EditText moneyEditId;
TextView dueId;
Calendar calendar;
float due;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.payment_layout);
final Long id = getIntent().getExtras().getLong(KeyConstants.STD_ID);
final String name = getIntent().getExtras().getString(KeyConstants.STD_NAME);
final String section = getIntent().getExtras().getString(KeyConstants.STD_SEC);
ListView listView = (ListView)findViewById(R.id.list_item);
List<Payments> paymentses = new ArrayList<>();
realm = Realm.getDefaultInstance();
getFee();
getPaidAmount(id,name,section);
totalFeeVew = (TextView)findViewById(R.id.totalFee);
paidId = (TextView)findViewById(R.id.my_payments_id);
payBtnId = (Button)findViewById(R.id.payment_id);
dueId = (TextView)findViewById(R.id.due_id);
moneyEditId = (EditText)findViewById(R.id.edit_amout_text_id);
totalFeeVew.setText(totalFee+"");
paidId.setText(paidAmount+"");
due = totalFee - paidAmount;
dueId.setText(due+"");
calendar = Calendar.getInstance();
paymentses = getPayments(id,name,section);
PaymentsAdapter adapter = new PaymentsAdapter(this,paymentses);
listView.setAdapter(adapter);
payBtnId.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addStudentFee();
}
});
}
private void getFee()
{
RealmResults<FeeDetails> users = realm.where(FeeDetails.class).findAll();
List<FeeDetails> feeDetailses = users;
if(feeDetailses != null && feeDetailses.size() != 0)
{
for(FeeDetails feeDetails : feeDetailses)
{
totalFee+=feeDetails.getAmount();
}
}
}
private void getPaidAmount(long id,String name,String section)
{
currentStudent = realm.where(Student.class).equalTo("name",name).equalTo("id",id).equalTo("section",section).findFirst();
paidAmount = currentStudent.getFee();
Log.i("current student","name "+currentStudent.getName());
Log.i("current student","Fee "+currentStudent.getFee());
}
private void addStudentFee()
{
String amount = moneyEditId.getText().toString();
moneyEditId.setText("");
if(amount !=null && amount.length() == 0)
{
return;
}
final float value = Float.parseFloat(amount);
// Update person in a transaction
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
currentStudent.setFee(currentStudent.getFee()+value);
}
});
createPayment(currentStudent,value);
}
private void createPayment(Student student,float payment)
{
realm.beginTransaction();
Payments transaction = realm.createObject(Payments.class);
transaction.setName(student.getName());
transaction.setSection(student.getSection());
transaction.setPayment(payment);
transaction.setPaymentDate(getCurrentDate());
transaction.setStudentId(student.getId());
realm.commitTransaction();
}
private String getCurrentDate()
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat format1 = new SimpleDateFormat("dd-mm-yyyy");
System.out.println(cal.getTime());
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
return formatted;
}
private List<Payments> getPayments(long id,String name,String section)
{
RealmResults<Payments> paymentses = realm.where(Payments.class).equalTo("name",name).findAll();
List<Payments> paymentses1 = paymentses;
if(paymentses1 == null)
{
paymentses1 = new ArrayList<>();
}
Log.i("size","size is "+paymentses1.size());
return paymentses1;
}
}
<file_sep>package com.tracker.student.student99.activities;
import android.app.Activity;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.tracker.student.student99.R;
import com.tracker.student.student99.models.Student;
import io.realm.Realm;
public class StudentCreateActivity extends Activity {
Realm realm;
EditText name;
EditText ageEdtText;
EditText fee;
EditText number;
EditText section;
EditText rollNoEdit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.student_creator);
realm = Realm.getDefaultInstance();
Button button = (Button)findViewById(R.id.create_id);
name = (EditText) findViewById(R.id.name_id);
ageEdtText = (EditText) findViewById(R.id.age_id);
fee = (EditText) findViewById(R.id.fee_id);
number = (EditText) findViewById(R.id.num_id);
section = (EditText) findViewById(R.id.sec_id);
rollNoEdit = (EditText) findViewById(R.id.roll_num_id);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String nameS = name.getText().toString();
String ageS = ageEdtText.getText().toString();
String feeS = fee.getText().toString();
String numberS = number.getText().toString();
String sectionS = section.getText().toString();
String rollNumberS = rollNoEdit.getText().toString();
long id = Long.parseLong(rollNumberS);
int age = Integer.parseInt(ageS);
long numberE = Long.parseLong(numberS);
Student student = new Student();
student.setName(nameS);
student.setSection(sectionS);
student.setFee(Float.parseFloat(feeS));
student.setId(id);
student.setAge(age);
student.setNumber(numberE);
Log.i("saved naumber","number "+numberE);
createNewStudent(student);
name.setText("");
ageEdtText.setText("");
fee.setText("");
number.setText("");
section.setText("");
rollNoEdit.setText("");
}
});
}
private void createNewStudent(Student student)
{
realm.beginTransaction();
Student transaction = realm.createObject(Student.class);
transaction.setName(student.getName());
transaction.setSection(student.getSection());
transaction.setFee(student.getFee());
transaction.setId(student.getId());
transaction.setNumber(student.getNumber());
realm.commitTransaction();
}
}
<file_sep>package com.tracker.student.student99.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.tracker.student.student99.R;
import com.tracker.student.student99.models.FeeDetails;
import java.util.List;
public class FeeStrutureAdapter extends BaseAdapter {
Context context;
List<FeeDetails> feeDetailses;
LayoutInflater inflater;
public FeeStrutureAdapter(Context context,List<FeeDetails> feeDetailses)
{
this.context = context;
this.feeDetailses = feeDetailses;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return feeDetailses.size();
}
@Override
public Object getItem(int i) {
return feeDetailses.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if(view == null)
{
viewHolder = new ViewHolder();
view = inflater.inflate(R.layout.fee_struc_layout,null);
viewHolder.details = (TextView) view.findViewById(R.id.details_id);
viewHolder.amount = (TextView) view.findViewById(R.id.amout_id);
view.setTag(viewHolder);
}
viewHolder = (ViewHolder)view.getTag();
viewHolder.details.setText(feeDetailses.get(i).getFeeDetails());
viewHolder.amount.setText(feeDetailses.get(i).getAmount()+"");
return view;
}
private static class ViewHolder
{
TextView details;
TextView amount;
}
}
<file_sep>package com.tracker.student.student99.models;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class Student extends RealmObject {
@PrimaryKey
private long id;
private String name;
private Long number;
private int age;
private String section;
private float fee;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public float getFee() {
return fee;
}
public void setFee(float fee) {
this.fee = fee;
}
public Long getNumber() {
return number;
}
public void setNumber(Long number) {
this.number = number;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
07b4657d72e4e102b2a4553fb810a5c4a7ce2c1b
|
[
"Java"
] | 5
|
Java
|
rkunche/student
|
7552d42143825c9db1db5e381de7f527d3815843
|
4f0f3f467d66a6d9989eb220be1707a11a60ded3
|
refs/heads/main
|
<file_sep>var taInput, divOutput;
var btnRun;
window.onload = function() {
taInput = document.getElementById('txtInput');
divOutput = document.getElementById('divOutput');
btnRun = document.getElementById('btnRun');
} //end window.onload
function runFwAlgo(){
divOutput.innerHTML="<p>Transitive Closure of the Relation Is:</p>"
FwAlgo();
//Get Input from
}//end run
S
function FwAlgo(){
var input_array = [];
var input_val = taInput.value;
var array_1 = input_val.split('\n');
var matrix_100 = [];
var matrix_1 = [];
var matrix_2 = [];
var matrix_3 = [];
var matrix_4 = [];
var matrix_5 = [];
var matrix_6 = [];
var matrix_7 = [];
var matrix_8 = [];
var matrix_9 = [];
var matrix_10 = [];
for (
var i = 0;
i < array_1.length;
i++
)
{
input_array[i] = array_1[i].split(',');
}
var box = input_array;
for(
var i = 0;
i < input_array.length;
i++
)
{
for(
var j=0;
j<input_array.length;
j++
)
{
box[i][j] = parseInt(input_array[i][j]);
}
}
divOutput.innerHTML += "Take Array";
divOutput.innerHTML += "<br />";
for(var i=0; i<100; i++) {
matrix_100[i] = [];
divOutput.innerHTML += "[";
for(var j=0; j<100; j++) {
var numb = '';
rand = Math.random();
if (rand > 0.5)
numb = 1;
else
numb = 0;
matrix_100[i][j] = numb;
divOutput.innerHTML += matrix_100[i][j] + ' ';
}
divOutput.innerHTML += "]";
divOutput.innerHTML += "<br />";
}
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "Array Warshall 1";
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "<br />";
for(var i=0; i<4; i++) {
matrix_1[i] = [];
for(var j=0; j<4; j++) {
var numb = matrix_100[i][j];
matrix_1[i][j] = numb;
//divOutput.innerHTML += matrix_1[i][j] + ' ';
}
}
console.log(matrix_1);
var count = matrix_1.length;
var result = matrix_1;
for (
var i = 0;
i < count;
i++
)
{
for (
var j = 0;
j < count;
j++
)
{
for (
var k = 0;
k < count;
k++
)
{
result[i][j] = ( result[i][j] || ( result[i][k] && result[k][j] ) );
}
}
if (i == count-1)
{
display(result);
}
}
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "Array Warshall 2";
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "<br />";
for(var i=0; i<4; i++) {
matrix_2[i] = [];
for(var j=4; j<8; j++) {
var numb = matrix_100[i][j];
matrix_2[i][j] = numb;
}
}
for(var i=0; i<matrix_2.length; i++) {
matrix_2[i] = matrix_2[i].filter(function (el) {
return el != null;
});
}
console.log(matrix_2);
var count = matrix_2.length;
var result = matrix_2;
for (
var i = 0;
i < count;
i++
)
{
for (
var j = 0;
j < count;
j++
)
{
for (
var k = 0;
k < count;
k++
)
{
result[i][j] = ( result[i][j] || ( result[i][k] && result[k][j] ) );
}
}
if (i == count-1)
{
display(result);
}
}
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "Array Warshall 3";
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "<br />";
for(var i=0; i<4; i++) {
matrix_3[i] = [];
for(var j=8; j<12; j++) {
var numb = matrix_100[i][j];
matrix_3[i][j] = numb;
}
}
for(var i=0; i<matrix_3.length; i++) {
matrix_3[i] = matrix_3[i].filter(function (el) {
return el != null;
});
}
console.log(matrix_3);
var count = matrix_3.length;
var result = matrix_3;
for (
var i = 0;
i < count;
i++
)
{
for (
var j = 0;
j < count;
j++
)
{
for (
var k = 0;
k < count;
k++
)
{
result[i][j] = ( result[i][j] || ( result[i][k] && result[k][j] ) );
}
}
if (i == count-1)
{
display(result);
}
}
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "Array Warshall 4";
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "<br />";
for(var i=0; i<4; i++) {
matrix_4[i] = [];
for(var j=12; j<16; j++) {
var numb = matrix_100[i][j];
matrix_4[i][j] = numb;
}
}
for(var i=0; i<matrix_4.length; i++) {
matrix_4[i] = matrix_4[i].filter(function (el) {
return el != null;
});
}
console.log(matrix_4);
var count = matrix_4.length;
var result = matrix_4;
for (
var i = 0;
i < count;
i++
)
{
for (
var j = 0;
j < count;
j++
)
{
for (
var k = 0;
k < count;
k++
)
{
result[i][j] = ( result[i][j] || ( result[i][k] && result[k][j] ) );
}
}
if (i == count-1)
{
display(result);
}
}
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "Array Warshall 5";
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "<br />";
for(var i=0; i<4; i++) {
matrix_5[i] = [];
for(var j=16; j<20; j++) {
var numb = matrix_100[i][j];
matrix_5[i][j] = numb;
}
}
for(var i=0; i<matrix_5.length; i++) {
matrix_5[i] = matrix_5[i].filter(function (el) {
return el != null;
});
}
console.log(matrix_5);
var count = matrix_5.length;
var result = matrix_5;
for (
var i = 0;
i < count;
i++
)
{
for (
var j = 0;
j < count;
j++
)
{
for (
var k = 0;
k < count;
k++
)
{
result[i][j] = ( result[i][j] || ( result[i][k] && result[k][j] ) );
}
}
if (i == count-1)
{
display(result);
}
}
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "Array Warshall 6";
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "<br />";
for(var i=0; i<4; i++) {
matrix_6[i] = [];
for(var j=20; j<24; j++) {
var numb = matrix_100[i][j];
matrix_6[i][j] = numb;
}
}
for(var i=0; i<matrix_6.length; i++) {
matrix_6[i] = matrix_6[i].filter(function (el) {
return el != null;
});
}
console.log(matrix_6);
var count = matrix_6.length;
var result = matrix_6;
for (
var i = 0;
i < count;
i++
)
{
for (
var j = 0;
j < count;
j++
)
{
for (
var k = 0;
k < count;
k++
)
{
result[i][j] = ( result[i][j] || ( result[i][k] && result[k][j] ) );
}
}
if (i == count-1)
{
display(result);
}
}
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "Array Warshall 7";
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "<br />";
for(var i=0; i<4; i++) {
matrix_7[i] = [];
for(var j=24; j<28; j++) {
var numb = matrix_100[i][j];
matrix_7[i][j] = numb;
}
}
for(var i=0; i<matrix_7.length; i++) {
matrix_7[i] = matrix_7[i].filter(function (el) {
return el != null;
});
}
console.log(matrix_7);
var count = matrix_7.length;
var result = matrix_7;
for (
var i = 0;
i < count;
i++
)
{
for (
var j = 0;
j < count;
j++
)
{
for (
var k = 0;
k < count;
k++
)
{
result[i][j] = ( result[i][j] || ( result[i][k] && result[k][j] ) );
}
}
if (i == count-1)
{
display(result);
}
}
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "Array Warshall 8";
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "<br />";
for(var i=0; i<4; i++) {
matrix_8[i] = [];
for(var j=28; j<32; j++) {
var numb = matrix_100[i][j];
matrix_8[i][j] = numb;
}
}
for(var i=0; i<matrix_8.length; i++) {
matrix_8[i] = matrix_8[i].filter(function (el) {
return el != null;
});
}
console.log(matrix_8);
var count = matrix_8.length;
var result = matrix_8;
for (
var i = 0;
i < count;
i++
)
{
for (
var j = 0;
j < count;
j++
)
{
for (
var k = 0;
k < count;
k++
)
{
result[i][j] = ( result[i][j] || ( result[i][k] && result[k][j] ) );
}
}
if (i == count-1)
{
display(result);
}
}
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "Array Warshall 9";
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "<br />";
for(var i=0; i<4; i++) {
matrix_9[i] = [];
for(var j=32; j<36; j++) {
var numb = matrix_100[i][j];
matrix_9[i][j] = numb;
}
}
for(var i=0; i<matrix_9.length; i++) {
matrix_9[i] = matrix_9[i].filter(function (el) {
return el != null;
});
}
console.log(matrix_9);
var count = matrix_9.length;
var result = matrix_9;
for (
var i = 0;
i < count;
i++
)
{
for (
var j = 0;
j < count;
j++
)
{
for (
var k = 0;
k < count;
k++
)
{
result[i][j] = ( result[i][j] || ( result[i][k] && result[k][j] ) );
}
}
if (i == count-1)
{
display(result);
}
}
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "Array Warshall 10";
divOutput.innerHTML += "<br />";
divOutput.innerHTML += "<br />";
for(var i=0; i<4; i++) {
matrix_10[i] = [];
for(var j=36; j<40; j++) {
var numb = matrix_100[i][j];
matrix_10[i][j] = numb;
}
}
for(var i=0; i<matrix_10.length; i++) {
matrix_10[i] = matrix_10[i].filter(function (el) {
return el != null;
});
}
console.log(matrix_10);
var count = matrix_10.length;
var result = matrix_10;
for (
var i = 0;
i < count;
i++
)
{
for (
var j = 0;
j < count;
j++
)
{
for (
var k = 0;
k < count;
k++
)
{
result[i][j] = ( result[i][j] || ( result[i][k] && result[k][j] ) );
}
}
if (i == count-1)
{
display(result);
}
}
//DISPLAY
function display(result){
var count = result.length;
for (
var i = 0;
i< count;
i++)
{
divOutput.innerHTML += "<br />";
for (
var j = 0;
j<count;
j++
)
{
divOutput.innerHTML += result[i][j];
divOutput.innerHTML += " ";
}
}<file_sep>
#DM 109 Fall 2020: Course Repository#
###PROJECT MEMBERS###
StdID | Name
------------ | -------------
**63338** | **<NAME>**
63292 | <NAME>
19283 | <NAME>
## Description ##
This repository contains assignments and project submitted to DM course offered in Fall 2020 at PafKiet.
<file_sep>var taInput = "", divOutput;
var btnRun;
window.onload = function() {
console.log("Hooray! Its working");
taInput = document.getElementById('txtInput');
divOutput = document.getElementById('divOutput');
btnRun = document.getElementById('btnRun');
} //end window.onload
function runFwAlgo(){
console.log("Running Floyd Warshall")
divOutput.innerHTML="<p>Transitive Closure of the Relation Is:</p>"
values = FwAlgo();
for(var i = 0; i < 4; i++)
{
divOutput.innerHTML+=values[i] + '<br />';
}
//Get Input from
}//end run
function FwAlgo(){
var graph = [];
for (i = 0; i < 4; ++i) {
graph.push([]);
for (j = 0; j < 4; ++j)
graph[i].push(i == j ? 0 : 9999999);
}
for (i = 1; i < 4; ++i) {
graph[0][i] = graph[i][0] = parseInt(Math.random() * 9 + 1);
}
for (k = 0; k < 4; ++k) {
for (i = 0; i < 4; ++i) {
for (j = 0; j < 4; ++j) {
if (graph[i][j] > graph[i][k] + graph[k][j])
graph[i][j] = graph[i][k] + graph[k][j]
}
}
}
return graph;
}//end sol1
|
68b06215cba483ff3592fa79987a14816b78770d
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
rafay97/DM-109-fall-2020
|
2f5719ad7145e53bffab736a540af3012337b784
|
ad5b9a3a69154f6efef61daf8698578de317460c
|
refs/heads/master
|
<repo_name>Pandapm/XiyouMobileFoundation<file_sep>/README.md
# XiyouMobileFoundation
XiyouMobile 公共类库
## 功能介绍
该类库旨在提供常用的C#开发工具类,目前包括公共工具部分、公共模型部分、ASP.NET MVC部分
## 公共工具部分
1.XYMHttpUtil -> HTTP请求工具类
## 公共模型部分
1.XYMWebApiUniResult -> 通用Result模型类
2.XYMHttpRequestModel -> 通用HTTP请求模型类
## WebAPI部分组成
1.XYMWebApiResult -> 用于返回JSON或JSONP数据
2.XYMWebApiResultManager -> 构建返回结果
## 欢迎继续补充
如有问题可发邮件至:<EMAIL>
<file_sep>/XiyouMobileFoundation/Utils/XYMHttpUtil.cs
/**
* Copyright (C) 2015 Xiyou Mobile Application Lab.
*
* XiyouMobileFoundation
*
* XYMHttpUtil.cs
*
* Created by <NAME> on 2015-5-5.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using XiyouMobileFoundation.Models;
using System.Diagnostics;
using System.IO;
namespace XiyouMobileFoundation.Utils
{
/// <summary>
/// HTTP请求工具类
/// </summary>
public class XYMHttpUtil
{
private const String RN = "\r\n";
private const String STRINGPARAM_FORMAT = "Content-Disposition: form-data; name=\"%s\"";
private const String FILEPARMA_FORMAT = "Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"";
private XYMHttpRequestModel requestModel;
private HttpWebRequest request;
private Stream requestStream;
private delegate object ResponseHandler(object obj);
public void DoRequestWithModel(XYMHttpRequestModel model)
{
requestModel = model;
try
{
request = (HttpWebRequest)HttpWebRequest.CreateDefault(new Uri(model.Url));
request.Method = model.Method.ToString();
request.CachePolicy = model.CachePolicy;
request.Timeout = model.Timeout;
request.KeepAlive = model.KeepAlive;
request.ContentType = model.ContentType;
AddHeaders(model.Headers);
}
catch (Exception e)
{
Debug.WriteLine(e.StackTrace);
}
if (model.Method == HttpMethod.POST)
{
using (requestStream = request.GetRequestStream())
{
BuildPostRequest();
}
}
}
private void AddHeaders(Dictionary<String, String> headers)
{
if (request != null && headers != null)
{
foreach (KeyValuePair<String, String> item in headers)
{
request.Headers.Add(item.Key, item.Value);
}
}
}
private void BuildPostRequest()
{
if (!requestModel.IsFileReqeuset)
{
}
}
}
}
|
9e2aa45b8fcc490ec085b183b158d3cb45971a3c
|
[
"Markdown",
"C#"
] | 2
|
Markdown
|
Pandapm/XiyouMobileFoundation
|
a2018f64a9f3a126c4286135c331f2d0bcc089af
|
1b701e3a671c922f19c5056017c7f3aad4846149
|
refs/heads/master
|
<file_sep>compile.on.save=true
user.properties.file=/Users/henriquegoebel/Library/Application Support/NetBeans/12.2/build.properties
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import Model.Cachorro;
import Model.Cavalo;
import Model.Gato;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
/**
*
* @author henriquegoebel
*/
public class FormAnimal extends javax.swing.JInternalFrame {
/**
* Creates new form FormAnimal
*/
public FormAnimal(TelaInicial telaInicial) {
initComponents();
lblTipoPelo.setVisible(false);
txtTipoPelo.setVisible(false);
lblVelocidade.setVisible(false);
txtVelocidade.setVisible(false);
lblCor.setVisible(false);
txtCor.setVisible(false);
this.telaInicial = telaInicial;
/*this.listaCachorro = listaCachorro;
listaGato = new ArrayList<Gato>();
listaCavalo = new ArrayList<Cavalo>();*/
}
public TelaInicial telaInicial;
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroupAnimal = new javax.swing.ButtonGroup();
lblAnimal = new javax.swing.JLabel();
rbCachorro = new javax.swing.JRadioButton();
rbGato = new javax.swing.JRadioButton();
rbCavalo = new javax.swing.JRadioButton();
lblNome = new javax.swing.JLabel();
txtNome = new javax.swing.JTextField();
lblID = new javax.swing.JLabel();
txtID = new javax.swing.JTextField();
lblPeso = new javax.swing.JLabel();
txtPeso = new javax.swing.JTextField();
lblVacina = new javax.swing.JLabel();
formattedtxtVacina = new javax.swing.JFormattedTextField();
lblTipoPelo = new javax.swing.JLabel();
txtTipoPelo = new javax.swing.JTextField();
lblVelocidade = new javax.swing.JLabel();
txtVelocidade = new javax.swing.JTextField();
lblCor = new javax.swing.JLabel();
txtCor = new javax.swing.JTextField();
btnCadastrar = new javax.swing.JButton();
setClosable(true);
setIconifiable(true);
setMaximizable(true);
setResizable(true);
setTitle("Formulário de Animal");
setPreferredSize(new java.awt.Dimension(800, 600));
try {
setSelected(true);
} catch (java.beans.PropertyVetoException e1) {
e1.printStackTrace();
}
lblAnimal.setText("Animal:");
buttonGroupAnimal.add(rbCachorro);
rbCachorro.setText("Cachorro");
rbCachorro.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
rbCachorroStateChanged(evt);
}
});
buttonGroupAnimal.add(rbGato);
rbGato.setText("Gato");
rbGato.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
rbGatoStateChanged(evt);
}
});
buttonGroupAnimal.add(rbCavalo);
rbCavalo.setText("Cavalo");
rbCavalo.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
rbCavaloStateChanged(evt);
}
});
lblNome.setText("Nome:");
lblID.setText("Número de Identificação:");
lblPeso.setText("Peso (em kgs):");
lblVacina.setText("Data da última vacina:");
try {
formattedtxtVacina.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
lblTipoPelo.setText("Tipo de Pelo (curto ou longo):");
lblVelocidade.setText("Velocidade Máxima (em km/h):");
lblCor.setText("Cor:");
btnCadastrar.setText("Cadastrar");
btnCadastrar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btnCadastrarMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(41, 41, 41)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnCadastrar)
.addGroup(layout.createSequentialGroup()
.addComponent(lblAnimal)
.addGap(18, 18, 18)
.addComponent(rbCachorro)
.addGap(18, 18, 18)
.addComponent(rbGato)
.addGap(18, 18, 18)
.addComponent(rbCavalo))
.addGroup(layout.createSequentialGroup()
.addComponent(lblNome)
.addGap(18, 18, 18)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(lblID)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(lblPeso)
.addGap(26, 26, 26)
.addComponent(txtPeso, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(lblVacina)
.addGap(18, 18, 18)
.addComponent(formattedtxtVacina, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(lblTipoPelo)
.addGap(18, 18, 18)
.addComponent(txtTipoPelo, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(lblCor)
.addGap(18, 18, 18)
.addComponent(txtCor, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(lblVelocidade))
.addGap(18, 18, 18)
.addComponent(txtVelocidade, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(373, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblAnimal)
.addComponent(rbCachorro)
.addComponent(rbGato)
.addComponent(rbCavalo))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblNome)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblID)
.addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblPeso)
.addComponent(txtPeso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblVacina)
.addComponent(formattedtxtVacina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblTipoPelo)
.addComponent(txtTipoPelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblVelocidade)
.addComponent(txtVelocidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblCor)
.addComponent(txtCor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(42, 42, 42)
.addComponent(btnCadastrar)
.addContainerGap(84, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/*public List<Cachorro> listaCachorro;
public List<Gato> listaGato;
public List<Cavalo> listaCavalo;
public List<Cachorro> getListaCachorro() {
return listaCachorro;
}
public List<Gato> getListaGato() {
return listaGato;
}
public List<Cavalo> getListaCavalo() {
return listaCavalo;
}*/
private void rbCachorroStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_rbCachorroStateChanged
if(rbCachorro.isSelected()){
lblTipoPelo.setVisible(true);
txtTipoPelo.setVisible(true);
lblVelocidade.setVisible(false);
txtVelocidade.setVisible(false);
lblCor.setVisible(false);
txtCor.setVisible(false);
}
}//GEN-LAST:event_rbCachorroStateChanged
private void rbGatoStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_rbGatoStateChanged
if(rbGato.isSelected()){
lblTipoPelo.setVisible(false);
txtTipoPelo.setVisible(false);
lblVelocidade.setVisible(false);
txtVelocidade.setVisible(false);
lblCor.setVisible(true);
txtCor.setVisible(true);
}
}//GEN-LAST:event_rbGatoStateChanged
private void rbCavaloStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_rbCavaloStateChanged
if(rbCavalo.isSelected()){
lblTipoPelo.setVisible(false);
txtTipoPelo.setVisible(false);
lblVelocidade.setVisible(true);
txtVelocidade.setVisible(true);
lblCor.setVisible(false);
txtCor.setVisible(false);
}
}//GEN-LAST:event_rbCavaloStateChanged
private void btnCadastrarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCadastrarMouseClicked
/*JOptionPane.showMessageDialog(null, "Animal Cadastrado");*/
if(rbCachorro.isSelected()){
String textID = txtID.getText();
textID = textID.replace(",", ".");
int ID ;
ID = Integer.parseInt(textID);
String textTipoPelo = txtTipoPelo.getText();
String textNome = txtNome.getText();
String textVacina = formattedtxtVacina.getText();
String textPeso = txtPeso.getText();
double PesoC;
PesoC = Double.parseDouble(textPeso);
Cachorro c = new Cachorro(textTipoPelo, textNome, PesoC, ID, textVacina);
telaInicial.listaCachorro.add(c);
JOptionPane.showMessageDialog(null, "Cachorro Cadastrado");
}else if (rbGato.isSelected()){
String textID = txtID.getText();
textID = textID.replace(",", ".");
int ID ;
ID = Integer.parseInt(textID);
String textCor = txtCor.getText();
String textNome = txtNome.getText();
String textVacina = formattedtxtVacina.getText();
String textPeso = txtPeso.getText();
double PesoG;
PesoG = Double.parseDouble(textPeso);
Gato g = new Gato(textCor, textNome, PesoG, ID, textVacina);
telaInicial.listaGato.add(g);
JOptionPane.showMessageDialog(null, "Gato Cadastrado");
}else if(rbCavalo.isSelected()){
String textID = txtID.getText();
textID = textID.replace(",", ".");
int ID ;
ID = Integer.parseInt(textID);
String textVelocidade = txtVelocidade.getText();
String textNome = txtNome.getText();
String textVacina = formattedtxtVacina.getText();
String textPeso = txtPeso.getText();
double PesoCv;
PesoCv = Double.parseDouble(textPeso);
double VelCv;
VelCv = Double.parseDouble(textVelocidade);
Cavalo cv = new Cavalo(VelCv, textNome, PesoCv, ID, textVacina);
telaInicial.listaCavalo.add(cv);
JOptionPane.showMessageDialog(null, "Cavalo Cadastrado");
} else {
JOptionPane.showMessageDialog(null, "Por Favor Escolher Classe de Animal");
}
}//GEN-LAST:event_btnCadastrarMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCadastrar;
private javax.swing.ButtonGroup buttonGroupAnimal;
private javax.swing.JFormattedTextField formattedtxtVacina;
private javax.swing.JLabel lblAnimal;
private javax.swing.JLabel lblCor;
private javax.swing.JLabel lblID;
private javax.swing.JLabel lblNome;
private javax.swing.JLabel lblPeso;
private javax.swing.JLabel lblTipoPelo;
private javax.swing.JLabel lblVacina;
private javax.swing.JLabel lblVelocidade;
private javax.swing.JRadioButton rbCachorro;
private javax.swing.JRadioButton rbCavalo;
private javax.swing.JRadioButton rbGato;
private javax.swing.JTextField txtCor;
private javax.swing.JTextField txtID;
private javax.swing.JTextField txtNome;
private javax.swing.JTextField txtPeso;
private javax.swing.JTextField txtTipoPelo;
private javax.swing.JTextField txtVelocidade;
// End of variables declaration//GEN-END:variables
}
<file_sep>/*package view;
import Model.Cachorro;
import Model.Cavalo;
import Model.Gato;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
public class view {
public static void main(String[] args) {
String opcao = "s";
List<Cachorro> pc = new ArrayList<>();
List<Gato> gt = new ArrayList<>();
List<Cavalo> cl = new ArrayList<>();
while( ! opcao.equalsIgnoreCase( "n" )){
String texto = "Digite sua opção para cadastrar um Animal: \n" +
"1 - Cadastrar Cachorro \n" +
"2 - Remover Cachorro da Lista \n" +
"3 - Listar de todos os Cachorros Cadatrados \n" +
"4 - Cadastrar Gato \n"+
"5 - Remover Gato da Lista \n" +
"6 - Lista de todos os Gatos cadastrados \n" +
"7 - Cadastrar Cavalo \n" +
"8 - Remover Cavalo da Lista \n" +
"9 - Listar de todos os Cavalos Cadatrados \n" +
"n - Sair ";
opcao = JOptionPane.showInputDialog(texto);
switch( opcao ){
case "1":
Cachorro n = new Cachorro();
String id = JOptionPane.showInputDialog("Id do Animal");
id = id.replace(",", ".");
n.setId(Integer.valueOf( id ) );
String nome = JOptionPane.showInputDialog("Nome do Animal");
n.setNome(nome);
String tomouVacina = JOptionPane.showInputDialog("Data da última vacina");
n.setUltimaVacina(tomouVacina);
String peso = JOptionPane.showInputDialog("Qual o peso do Animal");
peso = peso.replace(",", ".");
n.setPeso(Double.valueOf( peso ) );
String tipoPelo = JOptionPane.showInputDialog("Tipo de pelo do Animal ====> Curto ou longo");
n.setTipoPelo(tipoPelo);
n.cadastrar();
pc.add(n);
break;
case "2":
int posn = Integer.valueOf( JOptionPane.showInputDialog("Informe a posição que deseja remover:") );
pc.remove(posn -1 );
break;
case "3":
String cont = "";
for (Cachorro pi : pc) {
cont += pi.listar()+ "\n";
}
JOptionPane.showMessageDialog(null, cont);
break;
case "4":
Gato g = new Gato();
String idd = JOptionPane.showInputDialog("Id do Animal");
id = idd.replace(",", ".");
g.setId(Integer.valueOf( idd ) );
String nomee = JOptionPane.showInputDialog("Nome do Animal");
g.setNome(nomee);
String tomouVacinaa = JOptionPane.showInputDialog("Data da última vacina");
g.setUltimaVacina(tomouVacinaa);
String pesoo = JOptionPane.showInputDialog("Qual o peso do Animal");
peso = pesoo.replace(",", ".");
g.setPeso(Double.valueOf( pesoo ) );
String cores = JOptionPane.showInputDialog("Quais cores do pelo do Animal");
g.setCor(cores);
g.cadastrar();
gt.add(g);
break;
case "5":
int posnn = Integer.valueOf( JOptionPane.showInputDialog("Informe a posição que deseja remover:") );
gt.remove(posnn -1 );
break;
case "6":
String contt = "";
for (Gato pi : gt) {
contt += pi.listar()+ "\n";
}
JOptionPane.showMessageDialog(null, contt);
break;
case "7":
Cavalo c = new Cavalo();
String iddd = JOptionPane.showInputDialog("Id do Animal");
id = iddd.replace(",", ".");
c.setId(Integer.valueOf( iddd ) );
String nomeee = JOptionPane.showInputDialog("Nome do Animal");
c.setNome(nomeee);
String tomouVacinaaa = JOptionPane.showInputDialog("Data da última vacina");
c.setUltimaVacina(tomouVacinaaa);
String pesooo = JOptionPane.showInputDialog("Qual o peso do Animal");
peso = pesooo.replace(",", ".");
c.setPeso(Double.valueOf( pesooo ) );
String velocidade = JOptionPane.showInputDialog("Qual a Velocidade do Animal?");
velocidade = velocidade.replace(",", ".");
c.setVelocidade(Double.valueOf( velocidade ) );
c.cadastrar();
cl.add(c);
break;
case "8":
int pposnn = Integer.valueOf( JOptionPane.showInputDialog("Informe a posição que deseja remover:") );
cl.remove(pposnn -1 );
break;
case "9":
String conttt = "";
for (Cavalo pi : cl) {
conttt += pi.listar()+ "\n";
}
JOptionPane.showMessageDialog(null, conttt);
break;
case "n":
break;
default:
JOptionPane.showMessageDialog(null, "Opção incorreta");
}
}
}
}
*/
|
96cdd2e3341db5600fb66d8500e0812bda7e5493
|
[
"Java",
"INI"
] | 3
|
INI
|
Silvana8686/PROJETOFINAL---POON2
|
0ec16ec38f74b138142319de7c1920cd2e1b7a66
|
f6f9f5fc4229c966b0633e34db1f99a148e11408
|
refs/heads/master
|
<repo_name>eartheekapat/COMP1521_rev<file_sep>/lab/2/sixteen_out.c
// Convert a 16-bit signed integer to a string of binary digits
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#define N_BITS 16
char *sixteen_out(int16_t value);
int main(int argc, char *argv[]) {
for (int arg = 1; arg < argc; arg++) {
long l = strtol(argv[arg], NULL, 0);
assert(l >= INT16_MIN && l <= INT16_MAX);
int16_t value = l;
char *bits = sixteen_out(value);
printf("%s\n", bits);
free(bits);
}
return 0;
}
// given a signed 16 bit integer
// return a null-terminated string of 16 binary digits ('1' and '0')
// storage for string is allocated using malloc
char *sixteen_out(int16_t value) {
// PUT YOUR CODE HERE
char *bit = malloc ((N_BITS+1) * sizeof(char));
assert(bit);
// check for 1 in each bit of value
// if 1 change the bit in bits to '1' instead of '0'
for (int i = 0; i < N_BITS; i++) {
int16_t bitmask = 1 << (N_BITS - i - 1);
if (value & bitmask) {
bit[i] = '1';
} else {
bit[i] = '0';
}
}
bit [N_BITS] = '\0';
return bit;
}
<file_sep>/lab/1/no_vowels.c
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define MAX_LEN 100
bool isVowel (char ch);
int main(void) {
char charBuff[MAX_LEN];
while (1) {
fgets(charBuff, MAX_LEN, stdin);
// loop through charBuff
for (int i = 0; charBuff[i] != '\0'; i++) {
if (!isVowel(charBuff[i])) {
printf("%c", charBuff[i]);
}
}
}
return 0;
}
bool isVowel (char ch) {
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' ||
ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U')
{
return true;
}
return false;
}
<file_sep>/lab/1/arg_stats.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
if (argc > 11) {
printf("Too many argument");
}
int min, max, sum, prod, mean;
for (int i = 1; i < argc; i++) {
// first loop assign the number to all
int num = strtol(argv[i], NULL, 10);
if (i == 1) {
min = num;
max = num;
sum = num;
prod = num;
mean = num;
} else {
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
sum += num;
prod *= num;
mean = sum / (argc - 1);
}
}
printf("MIN: %d\n", min);
printf("MAX: %d\n", max);
printf("SUM: %d\n", sum);
printf("PROD: %d\n", prod);
printf("MEAN: %d\n", mean);
return 0;
}
<file_sep>/lab/1/no_odd_lines.c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
int countChar (char line[]);
int main(void) {
char line[MAX_LEN];
while (fgets(line, MAX_LEN, stdin) != NULL) {
if (countChar(line) % 2 == 0) {
fputs(line, stdout);
}
}
}
int countChar (char line[]) {
int count_ch = 0;
for(int i = 0; line[i] != '\0'; i++) {
count_ch++;
}
return count_ch;
}<file_sep>/pet_struct.c
#include <stdio.h>
#include <stdlib.h>
struct pet
{
char name[20];
char type[10];
int age;
float weight;
};
int main () {
struct pet eg = {"Fluffy", "axolotl", 7, 300};
printf("%s %s %d %f", eg.name, eg.type, eg.age, eg.weight);
return 0;
}<file_sep>/binToHex.c
#include<stdio.h>
int main ()
{
long int binary, hexadecimal = 0, j = 1, remain;
printf ("Enter binary number: ");
scanf ("%ld", &binary);
while (binary != 0)
{
remain = binary % 10;
hexadecimal = hexadecimal + remain * j;
j = j * 2;
binary = binary / 10;
}
printf ("Hexadecimal value: %lX\n", hexadecimal);
return 0;
}<file_sep>/lab/1/my_args.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
printf("Program name: %s\n", argv[0]);
if (argc == 1) {
printf("There are no other arguments\n");
} else {
printf("There are %d arguments\n", argc-1);
for (int i = 1; i < argc; i++) {
printf("\tArgument %d is \"%s\"\n", i, argv[i]);
}
}
return 0;
}
<file_sep>/recursive.c
#include <stdio.h>
void printArrayRecur(int num[], int i);
int main(void)
{
int nums[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
printArrayRecur(nums, 0);
return 0;
}
void printArrayRecur(int num[], int i) {
int *num2 = num;
printf("%d\n", num[i]);
if (num[i+1] != 0) {
printArrayRecur(num2, i+1);
}
}<file_sep>/lab/1/collatz.c
#include <stdio.h>
#include <stdlib.h>
void recurFn (int n);
int main(int argc, char **argv)
{
if (argc != 2) {
printf("Usage: %s NUMBER", argv[0]);
return EXIT_FAILURE;
}
int n = strtol(argv[1], NULL, 10);
recurFn (n);
return EXIT_SUCCESS;
}
void recurFn (int n) {
int nextN;
if (n == 1) {
printf("%d\n", n);
} else if (n % 2 != 0) {
printf("%d\n", n);
nextN = 3*n + 1;
recurFn (nextN);
} else if (n % 2 == 0) {
printf("%d\n", n);
nextN = n / 2;
recurFn (nextN);
}
}
<file_sep>/lab/1/no_uppercase.c
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
bool isUpper (char ch);
int main(void) {
char ch;
while (scanf("%c", &ch) == 1) {
if (isUpper(ch)) {
printf("%c", ch+32);
} else {
printf("%c", ch);
}
}
return 0;
}
bool isUpper (char ch) {
if (ch >= 'A' && ch <= 'Z') {
return true;
} else {
return false;
}
}
|
7cbec03335a59d50907eea472b1251e38f7c41d9
|
[
"C"
] | 10
|
C
|
eartheekapat/COMP1521_rev
|
81962bface8084b8a7c945390685a88358d7d413
|
dacf2b93c481399ef8700b98e3c103b0a889dc84
|
refs/heads/master
|
<file_sep>#!/bin/bash
exec /usr/sbin/php-fpm5.5 -F > /dev/null 2>&1 & wait<file_sep>tag?=develop
build:
docker build --no-cache=true -t qoopido/php55:${tag} .
|
926558f2af995ae39c9908e8e113999a36f7f75a
|
[
"Makefile",
"Shell"
] | 2
|
Shell
|
dlueth/qoopido.docker.php55
|
971fc233e954460081b1cf7617b8938a5d69cd50
|
c22d5fe5d51e03ff27a23cd8f84200dc491aa743
|
refs/heads/master
|
<repo_name>2bellbree/moesif-express<file_sep>/app.js
/**
* Created by Xingheng on 10/16/16.
* This file is a simple test app.
*/
var express = require('express');
var app = express();
var moesifExpress = require('./lib');
var TEST_API_SECRET_KEY = '<KEY>';
var moesifMiddleWare = moesifExpress({applicationId: TEST_API_SECRET_KEY});
app.use(moesifMiddleWare);
app.get('/', function (req, res) {
res.json({a: 'abc'});
});
app.get('/abc', function (req, res) {
res.json({abc: 'abcefg'});
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
|
8d37b662936e9801038f29afaa170904cdd52e45
|
[
"JavaScript"
] | 1
|
JavaScript
|
2bellbree/moesif-express
|
34bfc4460fc89ee637eea3f9f0f8554250e5eafb
|
7e0283700cee7be55703120365649e0b554217df
|
refs/heads/main
|
<repo_name>Sakuraga200323/gibara-bot<file_sep>/run.py
import os
import traceback
import discord
import asyncio
from discord.ext import commands, tasks
from time import time
prefix = "a)"
token = os.environ['DISCORD_BOT_TOKEN']
c_id = 776328743458832384
loop = asyncio.get_event_loop()
async def run():
bot = MyBot()
try:
await bot.start(token)
except KeyboardInterrupt:
await bot.logout()
class MyBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix=commands.when_mentioned_or(prefix), loop=loop, case_insensitive=True, help_command=None)
self.load_extension("cogs.command")
self.now_time = int(time())
async def on_ready(self):
print("起動に成功しました")
self.wait_for_tao.start()
await self.get_channel(c_id).send("起動か再起動しました")
activity = discord.Game(name="a)help", type=3)
return await self.change_presence(status=discord.Status.do_not_disturb, activity=activity)
@tasks.loop(seconds=1.0)
async def wait_for_tao(self):
if int(time) >= self.now_time + 10:
await self.get_channel(c_id).send("起動か再起動しました")
self.now_time = int(time)
async def on_message(self, message):
user_id = message.author.id
if message.content.startswith(prefix):
return await self.process_commands(message)
if message.channel.id == c_id:
if user_id == 695288604829941781 and message.embeds and f"{self.user.mention}さん...\nゲームにログインしてね!!\n[コマンドは::loginだよ!!]" == message.embeds[0].description:
await asyncio.sleep(10)
await message.channel.send("::login")
await asyncio.sleep(10)
await message.channel.send("::t")
self.now_time = int(time)
if user_id == 664790025040429057:
await asyncio.sleep(1)
await message.channel.send(message.content)
await self.wait_for("message_edit", check=lambda b, a: a.channel.id == c_id and a.author.id == 695288604829941781)
await asyncio.sleep(3)
await message.channel.send("::t")
self.now_time = int(time)
async def on_command_error(ctx,exception):
if isinstance(exception,commands.CommandNotFound):
await ctx.send("そのコマンドは存在しない")
elif isinstance(exception,commands.MissingRequiredArgument):
await ctx.send("引数が足りてない")
else:
await ctx.send("例外発生 | {}".format(exception))
if __name__ == '__main__':
main_task = loop.create_task(run())
loop.run_until_complete(main_task)
loop.close()
|
08a2e565526b52539a2153d2d1ba64187f900162
|
[
"Python"
] | 1
|
Python
|
Sakuraga200323/gibara-bot
|
eec654a00d03b0e251ae104b160a3da1d8fd84c5
|
42148ef3a2c1624df715c5c2e2e06b74d10dd2d6
|
refs/heads/master
|
<repo_name>asadrasheed1/Banking<file_sep>/app/src/main/java/com/wow/app/banking/utilities/Constants.java
package com.wow.app.banking.utilities;
public class Constants {
public static final String TAG = "BANKING";
public static double INTEREST_RATE = 2.5;
}
|
efc518dd838a2906463a8152650fd0112cdc708e
|
[
"Java"
] | 1
|
Java
|
asadrasheed1/Banking
|
f0aaf02c4dba04f4d0b33bcf9feb4846ed61c3cb
|
c83391598bd93d7d6e0855a75cd59276716a66d2
|
refs/heads/master
|
<file_sep>class Song
the song is Tension by NAV
end<file_sep>class Post
the post is about how to automate your lifestyle
end<file_sep>class Artist
this artist is NAV
end
<file_sep>class Author
the authors name is <NAME>
end
|
5162f5326ce00cd7f44c84909974ed8f4f58031f
|
[
"Ruby"
] | 4
|
Ruby
|
kayathewriter/ruby-objects-has-many-lab-online-web-ft-120919
|
6081771cf89b0be6e770ce20df69eaab6dfa21b6
|
139fc819bfa697b6fe5dbc3214b78003469bcec3
|
refs/heads/master
|
<repo_name>EYALYAFFE/ML<file_sep>/decision_tree_exercise3.py
#%%
import pandas as pd
import numpy as np
url="http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data"
data=pd.read_csv(url)
data=data.values
train_data=data[0:100,:] #this is the train data
test_data=data[100:568,:] #this is the test data
#%%
import math
def calcGini(data,feature,mean):
small=np.empty([0, 32], dtype=float) #just an empty array
big=np.empty([0, 32], dtype=float) #another an empty array
size_of_data=(len(data))
for row_index in range(size_of_data):
row = data[row_index,:]
if data[row_index,feature]<mean:
small = np.vstack([small,row])
if data[row_index,feature]>=mean:
big = np.vstack([big,row])
small_impurity=calcImpurity(small)
big_impurity=calcImpurity(big)
tsize=len(data)
ssize=len(small)
bsize=len(big)
avg_ampurity=(ssize/tsize)*small_impurity+(bsize/tsize)*big_impurity
return avg_ampurity
def calcImpurity(data):
if (data.size==0):
return 0
b_count=len(data[data[:,1]=='B'])
m_count=len(data[data[:,1]=='M'])
size=len(data)
return 1-math.pow(b_count/size,2)-math.pow(m_count/size,2)
def calcFeatureAndValue(data):
min_gini=1
for feature in range(2,32):
for row in range(len(data)):
temp_gini=calcGini(data,feature,data[row][feature])
if (temp_gini<min_gini):
min_gini=temp_gini
column=feature
value=data[row][feature]
return column, value
class node:
def __init__(self,data,deapth):
self.deapth=deapth
self.data=data
self.isleaf=False
def buildTree(self):
T_F, M_or_B=allDataLabelsAreSame(self.data)
if (T_F):
self.isleaf=True
self.type=M_or_B
print(self.type,self.deapth)
return
self.feature, self.value=calcFeatureAndValue(self.data)
s1,s2=split(self.data,self.feature,self.value)
self.left=node(s1,self.deapth+1)
self.right=node(s2,self.deapth+1)
self.left.buildTree()
self.right.buildTree()
def predict(self,row):
if (self.isleaf==True):
return self.type
if (row[self.feature]<self.value):
return self.left.predict(row)
if (row[self.feature]>=self.value):
return self.right.predict(row)
def allDataLabelsAreSame(data):
b_count=0
m_count=0
if (not data.size == 0):
b_count=len(data[data[:,1]=='B'])
m_count=len(data[data[:,1]=='M'])
size=len(data)
if (size==b_count):
return True, "B"
if (size==m_count):
return True, "M"
return False,"NONE"
def split(data,feature,mean):
small=np.empty([0, 32], dtype=float)
big=np.empty([0, 32], dtype=float)
for i in range(len(data)):
row=data[i]
if data[i][feature]<mean:
small = np.vstack([small,row])
if data[i][feature]>=mean:
big = np.vstack([big,row])
return small,big
root = node(train_data,0)
root.buildTree()
def displayAccuracy(model,test_data):
counter=0
for i in range(len(model)):
if (model[i]==test_data[i]):
counter+=1
return (counter/(len(model)))*100
model=[]
for i in range(len(test_data)):
model.append(root.predict(test_data[i]))
test_data_as_list=list(test_data[:,1])
print(displayAccuracy(model,test_data_as_list))<file_sep>/logistic regression - solution.py
import numpy as np
import scipy.stats as stats
from matplotlib import pyplot as plt
#np.random.seed(5)
def generate_random_clusters(n_points_in_cluster,n_clusters, std):
center = np.random.rand(2)*4
angles = 2*np.pi* np.linspace(0,1,n_clusters+1)[:-1]
centers = np.c_[np.cos(angles),np.sin(angles)] + center
noise = np.random.normal(0,std,(n_clusters,n_points_in_cluster,2))
points = np.repeat(np.expand_dims(centers,1),n_points_in_cluster,axis=1)
return points + noise
n_points_in_cluster = 99
n_clusters = 2
std = 0.8
data = generate_random_clusters(n_points_in_cluster,n_clusters, std)
data_points=data.reshape(-1,2)
import matplotlib.cm as cm
colors = cm.rainbow(np.linspace(0, 1, n_clusters))
nn=n_points_in_cluster
for i in range(n_clusters):
plt.scatter(data_points[nn*i:nn*(i+1),0],data_points[nn*i:nn*(i+1),1],color=colors[i])
y=np.repeat(np.array(range(n_clusters)),n_points_in_cluster)
X = np.c_[data_points,np.ones(data_points.shape[0])]
def split_train_test(X,y,percentage_test):
per_index=int(len(y)*(1-percentage_test))
return X[:per_index,...],X[per_index:,...],y[:per_index],y[per_index:]
percentage_test = 0.2
indices= np.array(range(n_points_in_cluster*n_clusters))
np.random.shuffle(indices)
X_train, X_test, y_train, y_test = split_train_test(X[indices,:],y[indices],percentage_test)
def logit(x):
return 1/(1+ np.exp(-x))
#def softmax(x):
# exp_norm = np.exp(x-x.max())
# return exp_norm/exp_norm.sum(axis=1)
EPS = 1e-7
def minus_log_likelihood(res,y):
return -(y*np.log(res+EPS)+(1-y)*np.log(1-res+EPS)).mean()
def predict_logit(x, teta):
return logit(np.dot(x,teta))>0.5
#def predict_softmax(x, teta):
# return softmax(np.dot(x,teta)).argmax()
def run_gradient_descent_logit(X,y,start,rate,epochs):
t=start.copy()
for epoch in range(epochs):
res=logit(np.dot(X,t))
loss=minus_log_likelihood(res,y)
grad=np.dot((res-y),X)/len(X)
t=t-rate*grad
print('epoch {}, loss {}, new t {}'.format(epoch,loss,t))
return t
start = np.append(np.random.normal(0,0.1,(2)),0)
teta = run_gradient_descent_logit(X_train,y_train,start,0.1,100)
train_precision=(predict_logit(X_train, teta)==y_train).sum()/len(y_train)
test_precision=(predict_logit(X_test, teta)==y_test).sum()/len(y_test)
print('Train precision: {} Test precision: {}'.format(train_precision, test_precision))
print(teta)
plt.figure()
def create_circles(n_points_in_cluster,n_clusters, std):
center = np.random.rand(2)*4
print('circle center: ', center)
angles = 2*np.pi*np.random.rand(n_clusters,n_points_in_cluster)
#radii =np.array([stats.truncnorm.rvs(-0.1+i,0.1+i,size=(n_points_in_cluster)) for i in range(2,2+n_clusters)])
arrays = []
for i in range(n_clusters):
arrays.append(np.random.normal(0,0.3,n_points_in_cluster)+2+i)
radii = np.array(arrays)
x_y_coords = np.array([radii*np.cos(angles)+center[0],radii*np.sin(angles)+center[1]])
# The two swap axes will re-shuffle the dimensions to the order of n_clusters X n_points_in_cluster X Coordinates
return np.swapaxes(np.swapaxes(x_y_coords,0,2),0,1)
circles=create_circles(n_points_in_cluster,n_clusters, std)
for i in range(circles.shape[0]):
# plot each set of points
plt.scatter(circles[i,:,0],circles[i,:,1],color=colors[i])
# define coundaries of plot
plt.xlim(circles[:,:,0].min(),circles[:,:,0].max())
plt.ylim(circles[:,:,1].min(),circles[:,:,1].max())
data_points=circles.reshape(-1,2)
X=data_points
# create labels
y=np.repeat(np.array(range(n_clusters)),n_points_in_cluster)
#X = np.c_[data_points,np.ones(data_points.shape[0])]
indices= np.array(range(n_points_in_cluster*n_clusters))
np.random.shuffle(indices)
X_train, X_test, y_train, y_test = split_train_test(X[indices,:],y[indices],percentage_test)
def model_prediction(X,t):
circle_feature = (X[:,0]-t[0])**2 + (X[:,1]-t[1])**2 - t[2]**2
return logit(circle_feature)>0.5
def run_gradient_descent_circles_logit(X,y,start,rate,epochs):
t=start.copy()
for epoch in range(epochs):
res=model_prediction(X,t)
loss=minus_log_likelihood(res,y)
# Derivative of the circle formula for each t
model_grad_vec = -np.c_[2*(X[:,0]-t[0]), 2*(X[:,1]-t[1]),2*t[2]*np.ones(len(X))]
# pred - y is the combined derivative of cross entropy loss and logit (or softmax)
# We multiply it by the chain rule, the dot sums the results among different values of X, len applies average
grad=np.dot((res-y),model_grad_vec)/len(X)
t=t-rate*grad
print('epoch {}, loss {}, new t {}'.format(epoch,loss,t))
return t
#start = np.append(np.random.normal(0,0.1,(2)),0)
start = np.random.rand(3)*4
teta = run_gradient_descent_circles_logit(X_train,y_train,start,0.1,50)
train_precision=(model_prediction(X_train, teta)==y_train).sum()/len(y_train)
test_precision=(model_prediction(X_test, teta)==y_test).sum()/len(y_test)
print('Train precision: {} Test precision: {}'.format(train_precision, test_precision))
print(teta)
<file_sep>/Logistic regression.py
#%%
#1+2
import numpy as np
import matplotlib.pyplot as plt
import math
X1 = np.random.normal(8,2,(100,2)) ; Y1 = np.ones((100,1))
X2 = np.random.normal(13,2,(100,2)); Y2 = np.ones((100,1))
plt.scatter(X1[:,0],X1[:,1])
plt.scatter(X2[:,0],X2[:,1])
plt.show()
#%%
#3
Y=np.round(np.random.uniform(0,1,200))
X = np.vstack([X1,X2])
#%%
#4
def sigmoid(x):
return 1 / (1 + math.exp(-x))
#%%
#5
def prediction_of_logic(x):
if (x>=0.5):
return 1
else:
return 0
#%%
#6
def loss_function(X,Y,Hipothesis,)
return
<file_sep>/naive bayes.py
#%%
import numpy as np
from sklearn.model_selection import train_test_split
import pandas as pd
url = "pima-indians-diabetes.csv"
data = pd.read_csv(url)
X, y = data.iloc[:, :-1], data.iloc[:, -1]
kwargs = dict(test_size=0.22, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, **kwargs)
X_train.columns=['a','b','c','d','e','f','g','h']
X_test.columns=['a','b','c','d','e','f','g','h']
Train=X_train.assign(Class = y_train)
Zero_class=Train.loc[Train.loc[:,'Class']==0]
One_class=Train.loc[Train.loc[:,'Class']==1]
mean_std_table=np.arange(32,dtype='f').reshape((2, 16))
mean_std_table[0][0]=Zero_class.a.mean()
mean_std_table[0][1]=Zero_class.a.std()
mean_std_table[0][2]=Zero_class.b.mean()
mean_std_table[0][3]=Zero_class.b.std()
mean_std_table[0][4]=Zero_class.c.mean()
mean_std_table[0][5]=Zero_class.c.std()
mean_std_table[0][6]=Zero_class.d.mean()
mean_std_table[0][7]=Zero_class.d.std()
mean_std_table[0][8]=Zero_class.e.mean()
mean_std_table[0][9]=Zero_class.e.std()
mean_std_table[0][10]=Zero_class.f.mean()
mean_std_table[0][11]=Zero_class.f.std()
mean_std_table[0][12]=Zero_class.g.mean()
mean_std_table[0][13]=Zero_class.g.std()
mean_std_table[0][14]=Zero_class.h.mean()
mean_std_table[0][15]=Zero_class.h.std()
mean_std_table[1][0]=One_class.a.mean()
mean_std_table[1][1]=One_class.a.std()
mean_std_table[1][2]=One_class.b.mean()
mean_std_table[1][3]=One_class.b.std()
mean_std_table[1][4]=One_class.c.mean()
mean_std_table[1][5]=One_class.c.std()
mean_std_table[1][6]=One_class.d.mean()
mean_std_table[1][7]=One_class.d.std()
mean_std_table[1][8]=One_class.e.mean()
mean_std_table[1][9]=One_class.e.std()
mean_std_table[1][10]=One_class.f.mean()
mean_std_table[1][11]=One_class.f.std()
mean_std_table[1][12]=One_class.g.mean()
mean_std_table[1][13]=One_class.g.std()
mean_std_table[1][14]=One_class.h.mean()
mean_std_table[1][15]=One_class.h.std()
#%%
import math
def calculateProbability(x, mean, stdev):
exponent=math.exp(-(math.pow(x-mean,2)/(2*math.pow(stdev,2))))
return (1/(math.sqrt(2*math.pi)*stdev))*exponent
def calcProbabilty(X_test_row):
zero_probabilites=[]
ones_probabilties=[]
for i in range(len(X_test_row)):
temp_pzero = calculateProbability(X_test_row.iloc[i],mean_std_table[0][2*i],mean_std_table[0][2*i+1])
zero_probabilites.append(temp_pzero)
for i in range(len(X_test_row)):
temp_pone = calculateProbability(X_test_row.iloc[i],mean_std_table[1][2*i],mean_std_table[1][2*i+1])
ones_probabilties.append(temp_pone)
zeros_product=product(zero_probabilites)
ones_product=product(ones_probabilties)
if zeros_product>ones_product:
return 0
else:
return 1
def product(mylist):
ans=1
for i in range(len(mylist)):
ans=ans*mylist[i]
return ans
def findModelAccuracy(model,y_test):
counter=0
y_test=y_test.tolist()
for i in range(len(model)):
if model[i]==y_test[i]:
counter=counter+1
print(counter)
return counter/(len(model))
test_results=[]
for i in range(0,len(X_test)):
temp_result = calcProbabilty(X_test.iloc[i,:]) #returns 1 or 0
test_results.append(temp_result)
accuracy=findModelAccuracy(test_results, y_test)
print(accuracy)
<file_sep>/exam_solution_eyal_yaffe.py
"""
<NAME>
"""
#%%
#question 1
def reverse(string):
return string[::-1]
#test
#reverse("I am testing") #pass
#%%
#question 2
def overlapping(ls1, ls2):
ans = []
for element in ls1:
if element in ls2:
ans.append(element)
if len(ans)==0:
return False
else:
return True
#test
#print(overlapping([1,2,3],[4,5,6])) # return false and passed
#print(overlapping([1,2,3],[4,1,6])) # return true and passed
#%%
#question 3
import numpy as np
x = np.ones((4,4))
x[1:-1,1:-1]=0
#test
#print(x)
#%%
#question 4
import pandas as pd
url="https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv"
df=pd.read_csv(url,delimiter='\t',encoding='utf-8')
pd.set_option('display.expand_frame_repr', False)
df['item_price']=df['item_price'].str.replace('$','')
df['item_price']=df.item_price.astype(float)
print(df[df.item_price>10].item_price.nunique())
#%%
#question5
X=np.array([[0,1,2],[0,1,4],[1,1,1]]).T
Y=np.array([1,3,7])
Teta=np.array([2,2,0]).reshape(3,1)
alpha=1
def gradient_descent(x,y,teta, iterations,alpha):
for i in range(iterations):
Y_predicted=x @ teta
error=Y_predicted-y
teta=teta-alpha*(x.T@error/len(x))
print("iteration: {}, loss: {}".format(i,np.sum(error**2)))
gradient_descent(X,Y,Teta,3,0.1)
gradient_descent(X,Y,Teta,3,1)
"""
we can see that the lost in alpha=0.1 converges and when alpha is 1 its not.
the reason for not converging is because the weights (teta) is strongly effected by the learning rate.
we can conclude that function "jumps" to a point which is far from the local minimum
"""
#%%
#question 6
"""
an object is an instance of a class.
it is an abstract representation of aggregrated data unit.
it includes fields(attributes) and methods.
object are held in the heap section of the program memory and are deallocated by python garbage collector.
"""
#%%
#question7
class animal:
def __init__(self, number_of_legs):
self.number_of_legs=number_of_legs
def voice(self):
print("I am an animal!")
class cow(animal):
def __init__(self):
super().__init__(4) #calling animal constructoer
def voice(self): #overriding voice
print("I am a cow!")
class kengeroo(animal):
def __init__(self):
super().__init__(2)
def voice(self): #overriding voice
print("I am a kengeroo!")
class snake(animal):
def __init__(self):
super().__init__(0)
def voice(self):
print("I am a snake!")
#%%
#question 8 - KNN
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
url="https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
data = load_iris(url)
x_train, x_test, y_train, y_test = train_test_split(data[0],data[1],test_size=0.2,random_state=42)
from sklearn.neighbors import KNeighborsClassifier
neigh = KNeighborsClassifier(n_neighbors=3)
neigh.fit(x_train, y_train)
def findModelAccuracy(results,y_test):
counter=0
y_test=y_test.tolist()
for i in range(len(results)):
if results[i]==y_test[i]:
counter=counter+1
return counter/(len(results))
test_answers=[]
for i in range(len(x_test)):
temp_prediction=neigh.predict([x_test[i]])[0]
test_answers.append(temp_prediction)
print(findModelAccuracy(test_answers,y_test)) #100%! :-)
#%%
#question 8 - logisitc regression
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
url="https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
data = load_iris(url)
x_train, x_test, y_train, y_test = train_test_split(data[0],data[1],test_size=0.2,random_state=42)
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(random_state=0, solver='lbfgs',multi_class='multinomial').fit(x_train, y_train)
clf.predict(x_test[:2, :])
clf.predict_proba(x_test[:2, :])
#%%
#question 9
# I don't know
#%%
#question 10
"""
A[-1 0] B[0.5 0] C[0 1] D[0 -1]
[0 -1] [0 0.5] [1 0] [1 0]
"""<file_sep>/pandas_advanced.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#%%
#part3
pd.set_option('display.max_columns', None)
url="https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/US_Crime_Rates/US_Crime_Rates_1960_2014.csv"
crime=pd.read_csv(url,delimiter='\,',encoding='utf-8')
pd.set_option('display.expand_frame_repr', False)
print(crime.head(20))
#%%
#4
print(crime.dtypes)
#%%
#5
crime.Year = pd.to_datetime(crime.Year, format='%Y')
print(crime.dtypes)
#%%
#6
crime=crime.set_index('Year')
#%%
#7
crime=crime.drop(columns=['Total'],axis=1)
#%%
#8
print(crime.groupby((crime.index.year//10)*10).sum())
#%%
#9
#TBD
#%%
#PART 2
baby_names = pd.read_csv("NationalNames.csv")
print(baby_names.head(2000000))
#%%
#ex6
print(baby_names.groupby('Gender').count())
#%%
#ex7
#%%
#ex8
#%%
#ex9
print(baby_names['Name'].value_counts().argmax())
#%%
#ex10
#How many different names have the least occurrences?
names=baby_names.groupby('Name').count()
names_are_one=names.loc[names['Count'] == 1]
print(names_are_one.count())
#%%
#ex11
print(names.median())
#%%
#ex12
print(names.std())
#%%
#ex13
print(names.describe())
#%%
#PART 3
pd.set_option('display.max_columns', None)
url="https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv"
chipo=pd.read_csv(url,delimiter='\t',encoding='utf-8')
pd.set_option('display.expand_frame_repr', False)
print(chipo.head(10))
#%%
#5
top_bought=chipo.groupby('item_name').size()
top_5_items=top_bought.sort_values('index',ascending=False).head(5)
top_5_items=top_5_items.to_frame()
top_5_items.T.plot(kind = "hist",bins=30)
#%%
#PART 4
<file_sep>/ex3_panda.py
#%%
#ex1
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#%%
#ex2+ex3+ex4
url="https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv"
chipo=pd.read_csv(url,delimiter='\t',encoding='utf-8')
pd.set_option('display.expand_frame_repr', False)
print(chipo.head(20))
#%%
#ex5
print(len(chipo.index))
#%%
#ex6
print(len(chipo.columns))
#%%
#ex7
print(chipo.columns)
#%%
#ex8
print(chipo.index)
#%%
#ex9
chipo9=chipo.groupby(['item_name']).size().argmax()
print(chipo9)
#%%
#ex10 How many items were ordered?
Total = chipo['quantity'].sum()
print(Total)
#%%
#ex11
print(chipo.groupby('choice_description').choice_description.count().argmax())
#%%
#ex12
#same as 10
#%%
#ex13
chipo['item_price']=chipo['item_price'].str.replace('$','')
print(chipo)
chipo['item_price']=chipo.item_price.astype(float)
print(chipo.dtypes)
#%%
#ex14
print(chipo[["quantity", "item_price"]].product(axis=1).sum())
#%%
#ex15
#same as previous questions
#%%
#ex16
print(chipo['item_price'].sum()/len(chipo.index))
#%%
#ex17
print(chipo.item_name.value_counts().count())
#%%
#part 2. Filtering & Sorting
#3
url="https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv"
chipo=pd.read_csv(url,delimiter='\t',encoding='utf-8')
pd.set_option('display.expand_frame_repr', False)
print(chipo.head(10))
#%%
#4
print(chipo[chipo.item_price > 10].item_price.count())
#%%
#5
print(chipo[chipo.quantity == 1][['item_name','item_price']].groupby('item_name'))
#%%
#6
print(chipo.sort_values(by=['item_name']))
#%%
#7
print(chipo.sort_values(by=['item_price']).tail(1).quantity)
#%%
#8
print(chipo.groupby("item_name").item_name.count()['Veggie Salad Bowl'])
#%%
#9
canned_soda = chipo['item_name'] == "Canned Soda"
qisgto = chipo['quantity'] > 1
print(chipo[canned_soda & qisgto])
print(len(chipo[canned_soda & qisgto].index))
#%%
#PART 3
url="https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user"
users=pd.read_csv(url,delimiter='|',encoding='utf-8')
pd.set_option('display.expand_frame_repr', False)
print(users.head(10))
#%%
#4
print(users.groupby("occupation").age.mean())
#%%
#5
mans = users[users.gender == 'M']
ans = mans.groupby('occupation').gender.count()
print(ans)
#%%
#6
print(users.groupby('occupation').age.max())
print(users.groupby('occupation').age.min())
#%%
#7
man=users[users.gender == 'M']
print(mans)
print(mans.groupby('occupation').age.mean())
woman=users[users.gender == 'F']
print(woman)
print(woman.groupby('occupation').age.mean())
#%%
#8
man=users[users.gender == 'M']
df_of_mans=mans.groupby('occupation').count().user_id
print(df_of_mans)
woman=users[users.gender == 'F']
df_of_womans=woman.groupby('occupation').count().age
print(df_of_womans)
temp=pd.concat([df_of_mans, df_of_womans], axis=1, join='inner')
print(temp)
temp["sum"] = temp.user_id+temp.age
temp["man_percentage"] = temp['user_id']/temp['sum']
temp["man_percentage"] = temp["man_percentage"]*100
print(temp)
#%%
#part 4. Merge
raw_data_1 = {
'subject_id': ['1', '2', '3', '4', '5'],
'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'last_name': ['Anderson', 'Ackerman', 'Ali', 'Aoni', 'Atiches']}
raw_data_2 = {
'subject_id': ['4', '5', '6', '7', '8'],
'first_name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'last_name': ['Bonder', 'Black', 'Balwner', 'Brice', 'Btisan']}
raw_data_3 = {
'subject_id': ['1', '2', '3', '4', '5', '7', '8', '9', '10', '11'],
'test_id': [51, 15, 15, 61, 16, 14, 15, 1, 61, 16]}
data1=pd.DataFrame(raw_data_1)
data2=pd.DataFrame(raw_data_2)
data3=pd.DataFrame(raw_data_3)
print(data1)
print(data2)
print(data3)
#%%
#question 4 Join the two dataframes along rows and assign all_data
all_data=pd.concat([data1,data2],ignore_index=True)
print(all_data)
#%%
#question 5
all_data_col = pd.concat([data1, data2], axis=1, sort=False)
print(all_data_col)
#%%
#question 7
print(all_data)
print(data3)
ans7 = pd.merge(all_data, data3)
print(ans7)
#%%
#question 8
ans8 = pd.merge(all_data,data3, on ="subject_id",how='inner')
print(ans8)
#%%
#PART 5
url="https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
iris=pd.read_csv(url,delimiter=',',encoding='utf-8')
pd.set_option('display.expand_frame_repr', False)
print(iris.head(10))
#%%
#4
iris.insert(5, "Team")
print(iris)
<file_sep>/self_exercise_DT.py
#%%
import pandas as pd
url="forest.csv"
data=pd.read_csv('Decision Tree DataSet.csv')
feature=data['outlook']
feature=feature.to_frame()
tree=createTree(data)
print(tree)
#%%
def createTree(data):
if
#%%
import numpy as np
def try_div(x,y):
if y==0:
return 0
return x/y
list_of_params=[]
def iParams(data, feature):
members=feature.iloc[:,0].unique()
entropi=0
for member in members:
member_instances=feature.loc[feature.outlook == member, feature.columns.values[0]].count()
yes_instances=data[(data[feature.columns.values[0]]== member) & (data.play == 'yes')].count()[0]
no_instances=data[(data[feature.columns.values[0]]== member) & (data.play == 'no')].count()[0]
comp1=-try_div(yes_instances,member_instances)*np.log2(try_div(yes_instances,member_instances))
comp2=-try_div(no_instances,member_instances)*np.log2(try_div(no_instances,member_instances))
entropi=comp1+comp2
list_of_params.append(entropi)
for n, i in enumerate(list_of_params):
if np.isnan(i):
list_of_params[n]=0
iParams(data, feature)
print(list_of_params)
#%%
import numpy as np
#ans1 = (-4/7)*(np.log2(4/7))-(3/7)*np.log2(3/7)
#ans2 = (-6/7)*(np.log2(6/7))-(1/7)*np.log2(1/7)
#ans3 = (-9/14)*(np.log2(9/14))-(5/14)*np.log2(5/14)
#print(ans3)
gain_forcest = 0.94-(5/14)*0.971*2
print(gain_forcest)
#%%
class Tree:
def __init__(self):
self.root=node("root")
def addNode(self,name):
self.root.addChild(name)
class Node:
def __init__(self, name):
self.name_of_node=name
self.list_of_childs=[]
def addChild(self, name):
self.list_of_childs.append(name)
<file_sep>/Naive Bayes solution.py
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 18 21:05:57 2018
@author: Lea
"""
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import math
#1
file_name = 'diabetes.csv'
data = pd.read_csv(file_name).values
x = data[:,:-1]
y = data[:,-1]
x_train,x_test,y_train,y_test = train_test_split(x,y)
#2
mean_x = np.mean(x,axis=0)
std_x = np.std(x,axis=0)
def mean_and_std_per_label(x,y,wanted_label):
x_with_specific_class = x[y==wanted_label]
mean = np.mean(x_with_specific_class,axis=0)
std = np.std(x_with_specific_class,axis=0)
return mean,std
def calc_mean_std(x,y):
mean_label_0,std_label_0 = mean_and_std_per_label(x,y,0)
mean_label_1,std_label_1 = mean_and_std_per_label(x,y,1)
return mean_label_0,std_label_0,mean_label_1,std_label_1
#3
#taken from equation of probability of Gaussian
def predict_gussian(x,mean,std):
prob_array = (1/(np.sqrt(2*math.pi)*std))*np.exp(-(x-mean)**2/(2*std**2))
prob_array = np.reshape(prob_array, (prob_array.shape[0],1))
prob = np.prod(prob_array,axis=0)
return prob
#4
def predict_on_dataset(x_values,mean_label_0,std_label_0,mean_label_1,std_label_1):
prob0 = []
prob1 = []
for row in x_values:
prob0_row = predict_gussian(row,mean_label_0,std_label_0)
prob1_row = predict_gussian(row,mean_label_1,std_label_1)
prob0.append(prob0_row)
prob1.append(prob1_row)
probabilities = np.column_stack( (prob0,prob1))
y_calculated = np.argmax(probabilities,axis=1)
return y_calculated
#5
def evaluate_predictions(x_test,y_test,mean0,std0,mean1,std1):
y_calculated = predict_on_dataset(x_test,mean0,std0,mean1,std1)
diff = y_calculated - y_test
wrong_points = np.sum(np.sqrt(diff**2) )
length = y_calculated.shape[0]
accuracy = 1-wrong_points/length
return accuracy
#6
class NaiveBayesClassifier():
def __init__(self):
self.alg_name = 'NaiveBayes'
self.mean0 = ''
self.std0 = ''
self.mean1 = ''
self.std1 = ''
def fit(self,x_train,y_train):
mean0,std0,mean1,std1 = calc_mean_std(x_train,y_train)
self.mean0 = mean0
self.mean1 = mean1
self.std0 = std0
self.std1 = std1
def predict(self,x_test):
prob0 = []
prob1 = []
for row in x_test:
prob0_row = predict_gussian(row,self.mean0,self.std0)
prob1_row = predict_gussian(row,self.mean1,self.std1)
prob0.append(prob0_row)
prob1.append(prob1_row)
probabilities = np.column_stack( (prob0,prob1))
y_calculated = np.argmax(probabilities)
return y_calculated
def evaluate(self,x_test,y_test):
accuracy = evaluate_predictions(x_test,y_test,self.mean0,self.std0,self.mean1,self.std1)
return accuracy
if __name__ == '__main__':
my_classifier = NaiveBayesClassifier()
my_classifier.fit(x_train,y_train)
accuracy = my_classifier.evaluate(x_test,y_test)
<file_sep>/ex2.py
#%%
#1
import numpy as np
#%%
#2
print(np.__version__)
#%%
#3
x=np.zeros(10,dtype=int)
print(x)
#%%
#4
x1=np.zeros(10,dtype=int)
print("nbytes:", x1.nbytes, "bytes")
#%%
#5
?np.add
#%%
#6
x=np.zeros(10,int)
x[4]=1
print(x)
#%%
#7
x=np.arange(10,50)
print(x)
#%%
#8
x1 = np.random.randint(10, size=10) # One-dimensional array
print(x1)
reversed_arr = x1[::-1]
print(reversed_arr)
#%%
#9
a = np.arange(9).reshape((3, 3))
print(a)
#%%
#10
a = np.array([1,2,0,0,4,0])
b=np.nonzero(a)
print(b)
#%%
#11
a=np.eye(3, dtype=int)
print(a)
#%%
#12
#a=np.random.rand(3,3,3)
print(a)
#%%
#13
a=np.random.randint(10, size=(10, 10))
min_num=a.min()
max_num=a.max()
print(a)
print(min_num)
print(max_num)
#%%
#14
x1 = np.random.randint(10, size=30)
print(x1)
a_mean=x1.mean();
print(a_mean)
#%%
#15
a=(5,5)
b=np.ones(a)
print(b)
b[1:-1,1:-1]=0
print(b)
#%%
#16
A = np.array([1,2,3,4,5])
np.pad(A, (1, 1), 'constant')
#%%
#17
print(0 * np.nan)
print(np.nan == np.nan)
print(np.inf > np.nan)
print(np.nan - np.nan)
print(0.3 == 3 * 0.1)
#%%
#18
diag=np.zeros((5,5),int)
print(diag)
np.fill_diagonal(diag, np.array([1,2,3,4,7]))
print(diag)
#%%
#19
b=np.ones((8,8),int)
b[1::2,::2] = 0
b[::2,1::2] = 0
print(b)
#%%
#20
print(np.unravel_index(100, (6,7,8)))
#%%
#21
z = np.tile(np.array([[0,1],[1,0]]), (4,4))
print(z)
#%%
#22
#%%
#23
arr = np.arange(1,9,dtype=np.int16).reshape((2,4))
print(arr.dtype)
#%%
#24
mat1 = np.arange(1,16).reshape((5,3))
mat2 = np.arange(1,7).reshape((3,2))
print(mat1)
print(mat2)
mat3=np.dot(mat1,mat2)
print(mat3)
#%%
#25
Z=np.arange(11)
Z[(3<Z)&(Z <= 8)] *= -1
print(Z)
#%%
#26
"""print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))"""
#%%
#27
Z=np.arange(11)
print(Z)
z1=Z**Z
print(z1)
z2=Z<-Z
z3=1j*Z
#%%
#28
#np.array(0) / np.array(0)
#np.array(0) // np.array(0)
#%%
#29
#%%
#30
z=np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1])
print(z)
#%%
#31
#done
#%%
#32
#print(np.sqrt(-1)==np.emath.sqrt(-1))
#%%
#33
yesterday=np.datetime64('today', 'D') - np.timedelta64(1, 'D')
print("Yestraday: ",yesterday)
today=np.datetime64('today', 'D')
print("Today: ",today)
tomorrow=np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print("Tomorrow: ",tomorrow)
#%%
#34
Z = np.arange('2016-08', '2016-09', dtype='datetime64[D]')
print(Z)
#%%
#35
A = np.array([1,2,3,4])
B = np.array([1,2,3,4])
print(A)
C=np.add(A, B)
print(C)
D=np.multiply(A,-0.5)
print(D)
print("************************")
E=np.multiply(C,D)
print(E)
#%%
#36
#36.1
import math
x = 1234.5678
y=math.modf(x) # (0.5678000000000338, 1234.0)
print(y)
#36.2
s = 1234.5678
i,d = divmod(s, 1)
print(i)
#%%
#37
import numpy as np
x = np.zeros((5,5))
print("Original array:")
print(x)
print("Row values ranging from 0 to 4.")
x += np.arange(5)
print(x)
#%%
#38-no exercise
#%%
#39
x = np.linspace(0,1,12,endpoint=True)[1:-1]
print(x)
#%%
#40
x = np.random.random(10)
print("Original array:")
print(x)
x.sort()
print("Sorted array:")
print(x)
####part 2####
#%%
#41
for dtype in [np.int8, np.int32, np.int64]:
print(np.iinfo(dtype).min)
print(np.iinfo(dtype).max)
for dtype in [np.float32, np.float64]:
print(np.finfo(dtype).min)
print(np.finfo(dtype).max)
print(np.finfo(dtype).eps)
#%%
#42
np.set_printoptions(threshold=np.nan)
Z = np.zeros((25,25))
print(Z)
#%%
#43
Z = np.arange(100)
print(Z)
v = np.random.uniform(0,100)
print(v)
index = (np.abs(Z-v)).argmin()
print(Z[index])
#%%
#44
Z = np.zeros(10, [ ('position', [ ('x', float, 1),
('y', float, 1)]),
('color', [ ('r', float, 1),
('g', float, 1),
('b', float, 1)])])
print(Z)
#%%
#45
Z = np.random.random((10,2))
print(Z)
X,Y = np.atleast_2d(Z[:,0]), np.atleast_2d(Z[:,1])
D = np.sqrt((X-X.T)**2 + (Y-Y.T)**2)
print(D)
#%%
#46
Z = np.arange(10, dtype=np.int32)
Z = Z.astype(np.float32, copy=False)
print(Z)
#%%
#47
#%%
#48
Z = np.arange(9).reshape(3,3)
for index, value in np.ndenumerate(Z):
print(index, value)
for index in np.ndindex(Z.shape):
print(index, Z[index])
#%%
#49
X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
D = np.sqrt(X*X+Y*Y)
sigma, mu = 1.0, 0.0
G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
print(G)
#%%
#50
n = 10
p = 3
Z = np.zeros((n,n))
np.put(Z, np.random.choice(range(n*n), p, replace=False),1)
print(Z)
#%%
#51
a=np.arange(9).reshape((3, 3))
print(a)
b=a-a.mean(axis=1,keepdims=True)
print(b)
#%%
#52
Z = np.random.randint(0,10,(3,3))
print(Z)
print(Z[Z[:,1].argsort()])
#%%
#53
Z = np.random.randint(0,3,(3,10))
print(Z)
print((~Z.any(axis=0)).any())
#%%
#54
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array-value)).argmin()
return array[idx]
array = np.random.random(10)
print(array)
value=0.5
print(find_nearest(array, value))
#%%
#55
class NamedArray(np.ndarray):
def __new__(cls, array, name="no name"):
obj = np.asarray(array).view(cls)
obj.name = name
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.info = getattr(obj, 'name', "no name")
Z = NamedArray(np.arange(10), "range_10")
print (Z.name)
#%%
#56
Z=np.ones(10)
print(Z)
I = np.random.randint(0,len(Z),20)
print(I)
Z += np.bincount(I, minlength=len(Z))
print(Z)
#%%
#57
<file_sep>/k nearest neighbours.py
#%%
#1
import numpy as np
from sklearn.datasets import load_iris
url="https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
data = load_iris(url)
#%%
#2
def distance_function(x1,x2):
sum = 0
for i in range(len(x1)):
sum += pow((x1[i]-x2[i]),2)
return np.sqrt(sum)
#test
print(distance_function(np.array([1,1,1]),np.array([0,0,0])))
#print(distance_function(data[0][0],data[0][1]))
#%%
#3
def getNeighborsAsindexs(k,x,dataset):
distances=[]
for i in range(len(dataset)):
temp_distance = distance_function(x,dataset[i])
distances.append(temp_distance)
return np.argsort(distances)[:k]
#print(getNeighborsAsindexs(10,np.array([0,0,0,0]),data[0]))
#%%
#4
def biggest(a, b, c):
Max=0
if b>Max:
Max=1
if c>Max:
Max=2
if b > c:
Max=1
return Max
def predict(x,neighbors_y):
counter_zero=0
counter_one=0
counter_two=0
for i in range(len(neighbors_y)):
if neighbors_y[i]==0:
counter_zero+=1
if neighbors_y[i]==1:
counter_one+=1
if neighbors_y[i]==2:
counter_two+=1
return biggest(counter_zero,counter_one,counter_two)
#%%
#5+6
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(data[0],data[1],test_size=0.2,random_state=42)
def calcYNeighborsBasedOnXindexs(indexes,dataset):
answers=[]
for i in range(len(indexes)):
answers.append(dataset[indexes[i]])
return answers
def calcAccuracy(x_train,x_test,y_train,y_test,k):
test_answers=[]
for i in range(len(x_test)):
neighbors_as_indexes=getNeighborsAsindexs(k,x_test[i],x_train)
neighbors_as_y_values=calcYNeighborsBasedOnXindexs(neighbors_as_indexes,y_train)
test_answers.append(predict(x_test[i],neighbors_as_y_values))
return test_answers
#test
ans=calcAccuracy(x_train,x_test,y_train,y_test,3)
print(*ans, sep=' ')
print(y_test)
#%%
#PART 2
<file_sep>/Gradient descent - solution.py
###########################
#### Gradient Descent #####
###########################
import numpy as np
x=np.array([0,1,2,3],dtype=np.float32)
y=np.array([1,3,7,13],dtype=np.float32)
X=np.c_[np.ones_like(x),x,x**2]
print(X)
# regression works nicely, but this is not part of the task
#check_regression(X,y)
start = np.array([2,2,0],dtype=np.float32)
def my_model(t):
return np.dot(X,t)
def mse_loss(res,y):
return 0.5*((res-y)**2).mean()
def mse_loss_grad(res,y):
return (np.dot(res-y,X))/len(X)
def run_gradient_descent(X,y,start,rate,epochs):
t=start.copy()
for epoch in range(epochs):
print(X.shape)
print(start.shape)
res=np.dot(X,t)
print(res)
loss=0.5*((res-y)**2).mean()
grad=(np.dot(res-y,X))/len(X)
t=t -rate*grad
print('epoch {}, loss {}, new t {}'.format(epoch,loss,t))
# This function is the same as the function above, with a breakdown of the matrix multiplications
def run_gradient_descent_for_loops(X,y,start,rate,epochs):
t=start.copy()
print(t)
for epoch in range(epochs):
res = np.zeros(len(X))
print(res)
for i in range(len(X)):
for j in range(len(t)):
res[i]= res[i] + X[i,j]*t[j]
loss=0.5*((res-y)**2).mean()
grads = np.zeros((len(X), len(t)))
for i in range(len(X)):
for j in range(len(t)):
grads[i,j] = (res[i]-y[i])*X[i,j]
grad = grads.mean(axis=0)
t=t -rate*grad
print('epoch {}, loss {}, new t {}'.format(epoch,loss,t))
run_gradient_descent(X,y,start,0.01,2)
def run_momentum_gradient_descent(X,y,start,model_function,rate,momentum_decay,epochs):
t=start.copy()
v=np.zeros_like(start)
for epoch in range(epochs):
res=np.dot(X,t)
loss=mse_loss(res,y)
grad=mse_loss_grad(res,y)
v=momentum_decay*v - rate*grad
t= t+v
print('epoch {}, loss {}, new t {}'.format(epoch,loss,t))
run_momentum_gradient_descent(X,y,start,my_model,0.01,0.9,1000)
def run_nesterov_momentum_gradient_descent(X,y,start,model,rate,momentum_decay,epochs):
t=start.copy()
v=np.zeros_like(start)
for epoch in range(epochs):
res=np.dot(X,t)
loss=mse_loss(res,y)
grad=mse_loss_grad(np.dot(X,t+momentum_decay*v),y)
v=momentum_decay*v - rate*grad
t= t+v
print('epoch {}, loss {}, new t {}'.format(epoch,loss,t))
run_nesterov_momentum_gradient_descent(X,y,start,my_model,0.01,0.9,1000)
<file_sep>/ex5_Gradient_Descent.py
#%%
#1.1
import numpy as np
X=np.array([[0,1,2],[0,1,4],[1,1,1]]).T
Y=np.array([1,3,7])
Teta=np.array([2,2,0]).reshape(3,1)
alpha=1
iterations=2
def gradient_descent(x,y,teta):
for i in range(iterations):
Y_predicted=x @ teta
error=Y_predicted-y
teta=teta-alpha*(x.T@error/len(x))
print("iteration: {}, loss: {}".format(i,np.sum(error**2)))
gradient_descent(X,Y,Teta)
#%%
#1.3
X=np.array([[0,1,2],[0,1,4],[1,1,1]]).T
Y=np.array([1,3,7])
Teta=np.array([2,2,0]).reshape(3,1)
alpha=0.1
gamma=0.9
iterations=50
def gradient_descent_momentum(x,y,teta,vt):
for i in range(iterations):
Y_predicted=x @ teta
error=Y_predicted-y
vt=gamma*vt+alpha*(x.T@error/len(x))
teta=teta-vt
print("iteration: {}, loss: {}".format(i,np.sum(error**2)))
gradient_descent_momentum(X,Y,Teta,0)
#%%
#1.4
X=np.array([[0,1,2],[0,1,4],[1,1,1]]).T
Y=np.array([1,3,7])
Teta=np.array([2,2,0]).reshape(3,1)
alpha=0.1
gamma=0.9
iterations=10
def gradient_descent_nestrov(x,y,teta,vt):
for i in range(iterations):
Y_predicted=x@(teta-vt*gamma)
error=Y_predicted-y
vt=gamma*vt+alpha*(x.T@error/len(x))
teta=teta-vt
# if i%100==0:
print("iteration: {}, loss: {}".format(i,np.sum(error**2)))
gradient_descent_nestrov(X,Y,Teta,0)
#%%
#2.2
def derive(x):
<file_sep>/decision_tree_exercise.py
#%%
import pandas as pd
url="http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data"
data=pd.read_csv(url)
test_data=data.head(68)
train_data=data.tail(500)
titles=[]
for i in range(32):
titles.append(i)
train_data.columns=titles
#%%
import math
import numpy as np
def prepareFeaturesAndMax():
columns=[]
for i in range(2,32):
columns.append(i)
return 0,0,columns
def calcFeatureAndValue(data):
temp_gain,max_gain, columns = prepareFeaturesAndMax()
for i in range(len(columns)):
mean=np.mean(data[columns[i]])
temp_gain=calcGain(data,columns[i],mean)
if temp_gain>max_gain:
max_gain=temp_gain
column=columns[i]
value = mean
return column, value
def calcGain(data, feature, value):
impurity_father=calcImpurityOfFather(data)
average_impurity_of_sons=calcWeightedImpurityOfSons(data,feature,value)
return impurity_father-average_impurity_of_sons
def calcImpurityOfFather(data):
if (data.empty):
return 0
b_count=data[1].str.count('B').sum()
m_count=data[1].str.count('M').sum()
size=len(data)
return 1-math.pow(b_count/size,2)-math.pow(m_count/size,2)
def calcWeightedImpurityOfSons(data,feature,value):
small = pd.DataFrame()
big = pd.DataFrame()
for i in range(len(data)):
row = data.iloc[[i]]
if data.iloc[i][feature]<value:
small = small.append(row)
if data.iloc[i][feature]>=value:
big = big.append(row)
small_impurity=calcImpurityOfFather(small)
big_impurity=calcImpurityOfFather(big)
tsize=len(data)
ssize=len(small)
bsize=len(big)
avg_ampurity=(ssize/tsize)*small_impurity+(bsize/tsize)*big_impurity
return avg_ampurity
class node:
def __init__(self,data,deapth):
self.deapth=deapth
self.data=data
self.isleaf=False
def buildTree(self):
T_F, M_or_B=allDataLabelsAreSame(self.data)
if (T_F):
self.isleaf=True
self.type=M_or_B
print(self.type,self.deapth)
return
self.feature, self.value=calcFeatureAndValue(self.data)
s1,s2=split(self.data,self.feature,self.value)
self.left=node(s1,self.deapth+1)
self.right=node(s2,self.deapth+1)
self.left.buildTree()
self.right.buildTree()
def predict(self,row):
if (self.isleaf==True):
return self.type
if (row.iloc[self.feature]<self.value):
return self.left.predict(row)
if (row.iloc[self.feature]>=self.value):
return self.right.predict(row)
def allDataLabelsAreSame(data):
b_count=data[1].str.count('B').sum()
m_count=data[1].str.count('M').sum()
size=len(data)
if (size==b_count):
return True, "B"
if (size==m_count):
return True, "M"
return False,"NONE"
def split(data,feature,value):
small = pd.DataFrame()
big = pd.DataFrame()
for i in range(len(data)):
row = data.iloc[[i]]
if data.iloc[i][feature]<value:
small = small.append(row)
if data.iloc[i][feature]>=value:
big = big.append(row)
return small,big
def displayAccuracy(model,test_data):
counter=0
for i in range(len(model)):
if (model[i]==test_data[i]):
counter+=1
return (counter/(len(model)))*100
root=node(train_data,0)
root.buildTree()
model=[]
for i in range(len(test_data)):
model.append(root.predict(test_data.iloc[i]))
test_data_as_list=list(test_data['M'])
print(displayAccuracy(model,test_data_as_list))
<file_sep>/ex1.py
import datetime
#ex1 by <NAME>
#1.1
print("Hello world")
#1.2
message = "Level Two"
print(message)
#1.3
print(type(message))
#1.4
a = 123
b = 654
c = a + b
#1.6
print(c)
a = 100
print(a) # think - should this be 123 or 100?
c = 50
print(c) # think - should this be 50 or 777?
d = 10 + a - c
print(d) # think - what should this be now?
#1.7
greeting = 'Hi '
name = 'Eyal'
message = greeting + name
print(message)
#1.8
age = 31
#print(name + ' is ' + age + ' years old')
#1.9
print(name + ' is ' + str(age) + ' years old')
age = '31'
print(name + ' is ' + age + ' years old')
#1.10
bobs_age = 15
your_age = 31
print(your_age == bobs_age)
#1.11
bob_is_older = bobs_age > your_age
print(bob_is_older)
#1.12
money = 500
phone_cost = 240
tablet_cost = 260
total_cost = phone_cost + tablet_cost
can_afford_both = money >= total_cost
if can_afford_both:
message = "You have enough money for both"
else:
message = "You can't afford both devices"
print(message)
raspberry_pi = 25
pies = 3 * raspberry_pi
total_cost = total_cost + pies
if total_cost <= money:
message = "You have enough money for 3 raspberry pies as well"
else:
message = "You can't afford 3 raspberry pies"
print(message)
#1.13
colours = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet']
print('Black' in colours)
colours.append('Black')
colours.append('White')
print('Black' in colours)
more_colours = ['Gray', 'Navy', 'Pink']
colours.extend(more_colours)
print(colours)
#1.14
primary_colours = ['Red', 'Blue', 'Yellow']
secondary_colours = ['Purple', 'Orange', 'Green']
main_colours = primary_colours + secondary_colours
print(main_colours)
#1.15
print(len(main_colours))
all_colours = colours + main_colours
print(len(all_colours))
#1.16
even_numbers = [2, 4, 6, 8, 10, 12]
multiples_of_three = [3, 6, 9, 12]
numbers = even_numbers + multiples_of_three
print(numbers, len(numbers))
numbers_set = set(numbers)
print(numbers_set, len(numbers_set))
colour_set = set(all_colours)
print(colour_set)
#1.17
my_class=['Sarah', 'Bob', 'Jim', 'Tom', 'Lucy', 'Sophie', 'Liz', 'Ed']
for student in my_class:
print(student)
my_class2=['classmate1','classmate2','etc']
my_class.extend(my_class2)
print(my_class)
for student in my_class:
print(my_class.index(student)+1,student)
#1.18
full_name = '<NAME>'
first_letter = full_name[0]
last_letter = full_name[19]
first_three = full_name[:3]
last_three = full_name[-3:]
middle = full_name[8:14]
print(middle)
#1.19
my_sentence = "Hello, my name is Fred"
parts = my_sentence.split(',')
print(parts)
print(type(parts))
my_long_sentence = "This is a very very very very very very long sentence"
parts2 = my_long_sentence.split(' ')
print(parts2,len(parts2))
#1.20
person = ('Bobby', 26)
print(person[0] + ' is ' + str(person[1]) + ' years old')
students = [('Dave', 12),('Sophia', 13),('Sam', 12), ('Kate', 11),('Daniel', 10)]
for student in students:
print(student)
#1.21
students=[('eyal', 31, 'subject1'),('david', 25, 'subject2'),('ariel', 45, 'subject3')]
for student in students:
print(student)
for student in students:
if student[1]>25:
print(student)
#1.22
addresses={'Lauren': '0161 5673 890',
'Amy': '0115 8901 165',
'Daniel': '0114 2290 542',
'Emergency': '999'
}
print(addresses['Amy'])
print('David' in addresses) # [False] #
print('Daniel' in addresses) # [True] #
print('999' in addresses) # [False] #
print('999' in addresses.values()) # [True] #
print(999 in addresses.values()) # [False]
addresses['Amy'] = '0115 236 359'
print(addresses['Amy'])
print('Daniel' in addresses) # [True] #
del addresses['Daniel'] #
print('Daniel' in addresses) # [False]
for name in addresses:
print(name, addresses[name])
#1.23
sum=0
for x in range(1001):
numAsString = str(x)
sumdigits = 0
for i in range(len(numAsString)):
sumdigits = sumdigits + int(str(i))
sum = sum+sumdigits
print(sum)
#1.24
def max(x,y):
if x>y:
return x
if y>x:
return y
else:
return x
print(max(5,3))
print(max(3,5))
#1.25
#assumes all diffrent
def max_of_three(x,y,z):
if x>y and x>z:
return x
if y>z and y>x:
return y
if z>y and z>y:
return z
print(max_of_three(1,2,3))
print(max_of_three(3,2,1))
print(max_of_three(1,3,2))
#1.26
def MyLength(string):
# Initialize count to zero
count=0
# Counting character in a string
for i in string:
count+= 1
# Returning count
return count
print(MyLength([1,2,3,4,5]))
print(MyLength("hello"))
#1.27
def isVowel(char):
if char=='a' or char=='u' or char=='i' or char=='o' or char=='e':
return True
else:
return False
print(isVowel('a'))
print(isVowel('b'))
#1.28
def translate(text):
ans=""
for i in range(0,len(text)):
if not isVowel(text[i]) and text[i]!=' ':
ans = ans + text[i]+'o'+text[i]
else:
ans = ans + text[i]
return ans
print(translate('this is fun'))
#part 2
#2.1
def devisibleby7(x):
ans = x % 7
if ans==0:
return True
else:
return False
def devisibleby5(x):
ans = x % 5
if ans==0:
return True
else:
return False
def devisibleby7andnotby5():
""":-)"""
for x in range(2000, 3201):
if devisibleby7(x) and not devisibleby5(x):
print(x, end=',')
print('***')
devisibleby7andnotby5()
#2.2 TBD
"""def factorial():
x=input()
result = 1
for i in range(2, int(x) + 1):
result *= i
return result
print(factorial())"""
"""2.3
y = input()
x = dict()
for i in range(1,int(y)+1):
x.update({i:i*i})
print(x)"""
#2.4
"""x = input()
y = x.split(',')
print(y)
z = tuple (y)
print(z)"""
#2.5
def square(x):
return x*x
print(square(5))
#2.6
print(abs.__doc__)
print(int.__doc__)
print(input.__doc__)
print(devisibleby7andnotby5.__doc__)
#2.7.6.a
class Triangle:
number_of_sides=3
def __init__(self,ang1,ang2,ang3):
self.ang1 = ang1
self.ang2 = ang2
self.ang3 = ang3
def check_angles(self):
sum=self.ang1+self.ang2+self.ang3
return sum==180
t1 = Triangle(4,5,6)
t2 = Triangle(90,45,45)
print(t1.number_of_sides)
print(t1.check_angles())
print(t2.check_angles())
my_triangle=Triangle(90,30,60)
class Song:
def __init__(self,lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for i in range(len(self.lyrics)):
print(self.lyrics[i])
happy_bday = Song(["May god bless you, ","Have a sunshine on you,","Happy Birthday to you!"])
happy_bday.sing_me_a_song()
class Lunch:
def __init__(self,menu):
self.menu=menu
def menu_price(self):
if self.menu=="menu 1":
print("Your choice: " + self.menu +"Price 12.00")
elif self.menu=="menu 2":
print("Your choice: " + self.menu +"Price 13.40")
else:
print("error in menu")
Paul = Lunch("menu 1")
Paul.menu_price()
class Point3D(object):
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
def __repr__(self):
print("(%d, %d, %d)" % (self.x, self.y, self.z))
my_point = Point3D(1,2,3)
my_point.__repr__()
#2.8.1
x=dict()
for i in range(101):
x.update({i:i*i})
print(x)
def isPrime(number):
for i in range(2,number):
if number%i==0:
return False
return True
ans=list()
for i in range(1,101):
if isPrime(i):
ans.append(i)
print(ans)
print(isPrime(10))
print(isPrime(5))
#f=open("eyal.txt","a+")
#f.write("hello world")
#f.close
#b=open("eyal.txt","w")
#b.close
#first_sentance=b.readline()
#print(first_sentance)
"""f=open("square_roots","w+")
for i in range(1,101):
x = square(i)
y=str(x)
f.write(y)
f.write("\n")"""
"""with open("eyal.txt","w+") as f:
data = "input data"
f.write(data)
with open("eyal.txt","r+") as f:
data = f.readlines()
print(data)"""
#2.11.1
data = "eyal is in Deep learning course"
data2 = data.split()
print(data2)
#2.11.2
"""print(" ".join(data2))
print("please enter first num")
x = input()
print("please enter second num")
y = input()
z = int(x)+int(y)
z=str(z)
print('the sum of %s and %s is %s' % (x,y,z))
print('the sum of {} and {} is {}.'.format(x,y,z))"""
#2.12
x=datetime.datetime.now()
print(x)
now = datetime.datetime.now()
dby =now-datetime.timedelta(days=2)
dif=now+datetime.timedelta(hours=12)
print(dby)
print(dif)
#%%
#2.13
try:
x=input()
y=int(x)
print(y)
except:
print("the input is not integer")
else:
print("Nothing went wrong")
#%%
#2.14
#%%
#2.15
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info('Start reading database')
# read database here
records = {'john': 55, 'tom': 66}
logger.debug('Records: %s', records)
logger.info('Updating records ...')
# update records here
logger.info('Finish updating records')
import logging
logging.basicConfig(filename='example.log',filemode="w",level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
#%%
#2.17
import os.path
home_folder = os.path.expanduser('~')
print(home_folder)
current=os.listdir(home_folder)
print(current)
#%%
#2.18
import glob
configfiles = glob.glob('C:/Users/User/Downloads/*.pdf')
print(configfiles)
#%%
#2.19
mylist=["zero","one","two","three","four", "five","six","seven","eight","nine"]
for i, item in enumerate(mylist):
print(i, item)
#%%
#2.20
import threading
def print1(num):
for i in range(0,num):
print(i,)
def print2(num):
for i in range(0,num):
print(i,)
if __name__ == "__main__":
t1 = threading.Thread(target=print1, args=(10,))
t2 = threading.Thread(target=print2, args=(10,))
t1.start()
t2.start()
# t1.join()
# t2.join()
print("Done!")
#%%
#2.21
import random, math
mylist=["zero","one","two","three","four", "five","six","seven","eight","nine"]
rand_number=math.ceil(random.uniform(0, 10.0)-1)
size_of_first_list=math.ceil(random.uniform(0, 10.0)-1)
size_of_second_list=10-size_of_first_list
print(size_of_first_list)
vector_of_selectd_indexs=[0,0,0,0,0,0,0,0,0,0]
mylist1=[]
mylist2=[]
i=0
while i<size_of_first_list:
temp_rand=math.ceil(random.uniform(0, 10.0)-1)
while vector_of_selectd_indexs[temp_rand]==1:
temp_rand=math.ceil(random.uniform(0, 10.0)-1)
mylist1.append(mylist[temp_rand])
vector_of_selectd_indexs[temp_rand]=1
i=i+1
i=0
while i<size_of_second_list:
temp_rand=math.ceil(random.uniform(0, 10.0)-1)
while vector_of_selectd_indexs[temp_rand]==1:
temp_rand=math.ceil(random.uniform(0, 10.0)-1)
mylist2.append(mylist[temp_rand])
vector_of_selectd_indexs[temp_rand]=1
i=i+1
print(mylist1)
print(mylist2) <file_sep>/ex4_linear_regression_implementation.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#%%
#1
X=pd.DataFrame([[31, 22], [22, 21], [40, 37], [26, 25]], columns=['Older sibling', 'Younger sibling'])
Y=pd.Series([2, 3, 8, 12])
Teta=np.dot(np.dot(np.linalg.inv(np.dot(X.T,X)),X.T),Y)
#Test
#print(Teta)
#%%
#1.2
X["Ones"] = [1,1,1,1]
print(X)
Teta=np.dot(np.dot(np.linalg.inv(np.dot(X.T,X)),X.T),Y)
#Test
print(Teta)
#%%
#PART 2
#2.1
df = pd.read_csv('data_for_linear_regression.csv')
#print(df)
#%%
#2.2
data=df.values
print(data)
#%%
#2.3
plt.scatter(data[:,0], data[:,1],alpha=1)
#%%
#2.4
X=data[0:200,0]
Z=np.ones((200, 1))
X=np.hstack((X.reshape(200,1),Z))
Y=data[0:200,1]
Teta=np.dot(np.dot(np.linalg.inv(np.dot(X.T,X)),X.T),Y)
print(Teta)
#%%
#2.5
plt.scatter(X[:,0],Y,alpha=1)
x_range=np.linspace(np.min(X[:,0]),np.max(X[:,0]), 1000)
y_range=x_range*Teta[0]+Teta[1]
plt.plot(x_range,y_range,c='red')
#%%
#2.6
<file_sep>/linear - regression - solution.py
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#1#############################
#
import numpy as np
X=np.array([[31,22],[22,21],[40,37],[26,25]])
y=np.array([2,3,8,12])
#def linear_regression(X,y):
# return np.dot(np.dot(np.linalg.inv(np.dot(X.transpose(),X)),X.transpose()),y)
def linear_regression(X,y):
dot = np.dot(X.transpose(),X)
#print(dot)
inv = np.linalg.inv(dot)
#print(inv)
inv_mul = np.dot(inv, X.transpose())
return np.dot(inv_mul,y)
def check_regression(X,y):
res=linear_regression(X,y)
print('Regression result: ',res)
print('predicted y:', np.dot(X,res))
print('loss :', ((np.dot(X,res)-y)**2).mean())
# 3D plane crossing (0,0,0)
check_regression(X,y)
# 3rd feature: constant
X1=np.ones((4,3))
X1[:,:-1]=X
check_regression(X1,y)
# 3rd feature: x1-x2
X2=X1.copy()
X2[:,2]=X[:,0]-X[:,1]
check_regression(X2,y)
# 3rd feature: (x1-x2)^2
X3=X1.copy()
X3[:,2]=(X[:,0]-X[:,1])**2
check_regression(X3,y)
# 3rd feature: (x1-x2)^2, 4th feature constant
X4=np.ones((4,4))
X4[:,:-1]=X3
check_regression(X4,y)
#2####################################################
max_num_points = 200
#2.1:
training_set = pd.read_csv('data_for_linear_regression.csv')
2.2
# Convert all data to matrix for easy consumption
x_training_set_ = training_set['x']
x_training_set_ = x_training_set_.values
#b = training_set['b'][1:10]
#b = b.values
x_training_set = x_training_set_[0:max_num_points]
y_training_set_ = training_set['y']
y_training_set_ = y_training_set_.values
y_training_set = y_training_set_[0:max_num_points]
#2.3:
plt.title('Relationship between X and Y')
plt.scatter(x_training_set, y_training_set, color='black')
plt.show()
#2.4:
b_ = np.ones((1,x_training_set_.shape[0]))
b = b_[:,0:max_num_points]
x_b = np.hstack((x_training_set.reshape(max_num_points, 1),b.reshape(max_num_points ,1)))
res = linear_regression(x_b, y_training_set)
print(res)
#2.5:
plt.hold
y_out = res[0]*x_training_set + res[1]*b
plt.plot(x_training_set, y_out.reshape(max_num_points,), color='red')
plt.show()
#2.6
plt.figure()
plt.title("test group")
y_out = res[0]*x_training_set_[max_num_points:] + res[1]*b_[:,max_num_points:]
plt.plot(x_training_set_[max_num_points:], y_out.reshape(500,), color='red')
plt.xlim((0,100))
plt.ylim(0,100)
plt.show()
plt.hold
plt.scatter(x_training_set_[max_num_points:], y_training_set_[max_num_points:], color='black')
<file_sep>/k nearest neighbours - solution.py
import numpy as np
from sklearn import datasets
iris_path=''
class DataSet():
def __init__(self, X,Y):
assert len(X)==len(Y) # sanity check
self.X=X
self.Y=Y
def train_test_random_split(self,p_train):
""" returns X_train, Y_train, X_test, Y_test according to percentaget
defined in p_train after randomly permuting the data """
assert 0<p_train<1
data_len=len(self.X)
train_len=round(p_train*data_len)
perm= np.random.permutation(data_len)
train_pos=perm[:train_len]
test_pos=perm[train_len:]
return self.X[train_pos],self.Y[train_pos],self.X[test_pos],self.Y[test_pos]
# property - enables calling function as as an attribute (this is a get property, set property also exist but has a different synthax)
@property
def std(self):
return self.X.std(axis=0),self.Y.std(axis=0)
@property
def mean(self):
return self.X.mean(axis=0),self.Y.mean(axis=0)
def distance(x,y):
return np.linalg.norm(x-y)
class KNN():
def __init__(self,X_train,Y_train, k):
self.X_train=X_train
self.Y_train=Y_train
self.k=k
@staticmethod #static method - a method which does not depend on an
# instance and acts exactly like any standalone method outside of a classe
# hence self is not passed as an argumetn
def majority_vote(y_labels):
votes={}
for label in y_labels:
if label in votes:
votes[label]+=1
else:
votes[label]=1
max_votes=0
result=None
for label,votes in votes.items():
if votes>max_votes:
max_votes=votes
result=label
return result
def _k_neighbours(self,point):
distances=[]
for i in range(len(self.X_train)):
distances.append((self.Y_train[i],distance(point,self.X_train[i])))
distances.sort(key=lambda tup: tup[1])
return distances[:self.k]
def _classify_point(self,point):
k_neighbours=self._k_neighbours(point)
labels=[tup[0] for tup in k_neighbours]
# we call the static method using the class name (though self also works)
return KNN.majority_vote(labels)
def train(self):
# no training in this model, we will se later why this was done
pass
def test(self,X_test):
results=[]
for i in range(len(X_test)):
results.append(self._classify_point(X_test[i]))
return(np.array(results))
def success_percentage(Y_test,Y_classified):
assert len(Y_test) == len(Y_classified)
return (Y_test==Y_classified).sum()/len(Y_test)
iris=datasets.load_iris()
data_set=DataSet(iris.data,iris.target)
# This is not part of KNN, just class demo
print('Data set mean: {}, and standart deviation: {}'.format(data_set.mean, data_set.std))
X_train,Y_train,X_test,Y_test=data_set.train_test_random_split(0.8)
knn=KNN(X_train,Y_train,3)
Y_classified=knn.test(X_test)
print('Success percentage {:.2%}'.format(success_percentage(Y_test,Y_classified)))
|
7e64ceeea2f72f7e65dc864a228befad1663d23d
|
[
"Python"
] | 18
|
Python
|
EYALYAFFE/ML
|
884e16b7e33288dcd5f8a5524cad7c67de2cc7e5
|
377693bdad8b77131e220d2f8eba44d98575588f
|
refs/heads/master
|
<repo_name>varun2948/touchpad_music<file_sep>/src/components/Cell.jsx
import React from "react";
import PropTypes from "prop-types";
import "./Cell.css";
function Cell(props) {
return (
<div className="gridItem" style={{ backgroundColor: props.color }}>
{props.children}
</div>
);
}
Cell.propTypes = {
color: PropTypes.string,
};
export default Cell;
<file_sep>/src/components/Keyboard.jsx
import React from "react";
import PropTypes from "prop-types";
import Cell from "./Cell";
import "./Keyboard.css";
const cells = Array.from({ length: 64 }, () => ({
color: "#000000",
}));
function Keyboard(props) {
return (
<div className="keyboardGrid">
{cells.map((c, i) => (
<Cell key={i} color={c.color} />
))}
</div>
);
}
Keyboard.propTypes = {};
export default Keyboard;
|
1b5d2f92c2a1805f56127e332f0aed740113f820
|
[
"JavaScript"
] | 2
|
JavaScript
|
varun2948/touchpad_music
|
ad65013769d0412bcd20310ad7971af3864c738e
|
ad3066dc9e80597a31cbab7a1d4aa4b992b062ef
|
refs/heads/master
|
<file_sep>### install vue & vue cli
```
npm install vue
```
- (https://vuejs.org/v2/guide/installation.html#NPM)
```
npm install -g @vue/cli
```
- (https://cli.vuejs.org/guide/installation.html)
### creating a project
```
vue create <nama-project>
```
- (https://cli.vuejs.org/guide/creating-a-project.html#vue-create
https://youtu.be/cP9bhEknW_g)
### using GUI
```
vue ui
```
### using plugin
```
vue add <nama-plugin>
```
### vuetify (vue UI library)
- [vuetify](https://vuetifyjs.com/en/)<file_sep>import Vue from "vue";
import Vuetify from "vuetify/lib/framework";
Vue.use(Vuetify);
export default new Vuetify({
theme: {
dark: true,
themes: {
dark: {
primary: '#240046',
secondary: '#10002B',
success: '#00C853',
warning: '#FFD600',
info: '#2962FF',
error: '#D50000'
}
}
}
});
|
b408688243e9281a2a003f5cc95432333d452b40
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
icalbalino/my-vue3
|
a38ed8377592a02237482f9c7a7d989f1c10ac8d
|
e0463814f3b29b55fb2eca38dad4045db79ae569
|
refs/heads/master
|
<file_sep># FashionMNIST NN
a fashion MNIST data NN model with 1 hidden layer
Simple 1 hidden layer NN developed from scratch.
784 nodes per instance input layer size.
300 nodes hidden layer size.
the model trained on 55k train samples labeled from 0-9.
MNIST data set 28X28 pictures already proccesed and convert to scale of 0-255.
tested on 5k test samples with 82.1% of accuracy.
feel free to use and adapt hyper parameters or methods.
instructions:
download python 3.6.
download numpy.
due to file size limitations the x_train set is divided to sub files.
in order to use the code properly you should merge those files.
linux:
1. enter the terminal and cd to the files path.
2. use the cat command as follows : **cat train_xaa train_xab train_xac train_xad train_xae train_xaf > train_x**
3. put the files in the same path/directory.
4. run the .py file and get your "test_y" output file.
<file_sep>import numpy as np
def predict(test, parameters):
MEM = forward_prop(test.T, parameters)
predictions = np.argmax(MEM["probabilities"], axis=0)
return predictions
def normalize(x):
x_normed = x / x.max(axis=0)
return x_normed
def update_parameters(parameters, gradients, eta):
parameters["W1"] = ((1 - (0.001 * eta)) * parameters["W1"]) - eta * gradients["dW1"]
parameters["B1"] = ((1 - (0.001 * eta)) * parameters["B1"]) - eta * gradients["db1"]
parameters["W2"] = ((1 - (0.001 * eta)) * parameters["W2"]) - eta * gradients["dW2"]
parameters["B2"] = ((1 - (0.001 * eta)) * parameters["B2"]) - eta * gradients["db2"]
return parameters
def log_min(vec, labels):
length = labels.shape[1]
logarithmic_probs = np.multiply(np.log(vec), labels)
loss = - np.sum(logarithmic_probs) / length
loss = np.squeeze(loss)
return loss
def forward_prop(x_train, parameters):
A1 = np.dot(parameters["W1"], x_train) + parameters["B1"]
Activation = normalize(re_lu(A1))
A2 = np.dot(parameters["W2"], Activation) + parameters["B2"]
Activation2 = re_lu(A2)
probabilities_vector = soft_max(Activation2.T)
MEM = {"A1": A1, "Activation": Activation, "A2": A2, "Activation2": Activation2,
"probabilities": probabilities_vector}
return MEM
def back_prop(parameters, mem, x_train, y_train):
length = len(y_train)
derivative2 = mem["probabilities"] - np.array(y_train).T
derivativeW2 = (1 / length) * np.dot(deravative2, (mem["Activation"]).T)
derivativeB2 = (1 / length) * np.sum(deravative2, axis=1, keepdims=True)
derivative1 = np.multiply(np.dot((parameters["W2"]).T, deravative2), 1 - np.square(mem["Activation"]))
derivativeW1 = (1 / length) * np.dot(deravative1, x_train)
derivativeB1 = (1 / length) * np.sum(deravative1, axis=1, keepdims=True)
gradients = {"dW1": deravativeW1,
"db1": deravativeB1,
"dW2": deravativeW2,
"db2": deravativeB2}
return gradients
def re_lu(x):
return x * (x > 0)
def soft_max(x):
x -= np.max(x)
sm = (np.exp(x).T / np.sum(np.exp(x), axis=1))
return sm
def translate(translator, data):
translated = []
for x in data:
translated.append(translator[x])
return translated
def main():
dictionary = {
0: 'T - shirt / top',
1: 'Trouser',
2: 'Pullover',
3: 'Dress',
4: 'Coat',
5: 'Sandal',
6: 'Shirt',
7: 'Sneaker',
8: 'Bag',
9: 'Ankleboot'
}
translator = {
0: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1: [0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
2: [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
3: [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
4: [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
5: [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
6: [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
7: [0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
8: [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
9: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
}
# random parameters.
np.random.seed(2)
Weights1 = np.random.uniform(-1, 1, (300, 784))
Bias1 = np.random.uniform(-1, 1, (300, 1))
Weights2 = np.random.uniform(-1, 1, (10, 300))
Bias2 = np.random.uniform(-1, 1, (10, 1))
Parameters_Dictionary = {"W1": Weights1, "W2": Weights2, "B1": Bias1, "B2": Bias2}
train_x = np.loadtxt("train_x")
train_y = np.loadtxt("train_y")
test_x = np.loadtxt("test_x")
train_y_vector = translate(translator, train_y)
# normalize brightness.
train_x /= 255
test_x /= 255
eta = 0.5
# try for 1200 iterations.
for iter in range(1200):
print(iter)
if iter % 300 == 0:
eta *= 0.95
mem = forward_prop(train_x.T, Parameters_Dictionary)
gradients = back_prop(Parameters_Dictionary, mem, train_x, train_y_vector)
Parameters_Dictionary = update_parameters(Parameters_Dictionary, gradients, eta)
predictions = predict(test_x, Parameters_Dictionary)
i = 0
fs = open("test_y", 'w+')
# write just the first 5k predictions.
for prediction in predictions:
if i == 5000:
break
fs.write(str(prediction))
fs.write('\n')
i += 1
fs.close()
# goto main()
if __name__ == "__main__":
main()
|
d37a4f31a3dc8f721887516d224c8bb3b2b19f3f
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
Bknisan/FashionMNISTNN
|
bf58a3242e34d66a593b81818dd9290ac4daaadf
|
cc9e94384dedb4f0e2f6c6a95b76e0cb84ed47c9
|
refs/heads/index_page
|
<file_sep>exports.enter = function(req, res) {
console.log("enter saindex.html");
res.sendfile("./views/saindex.html");
}
<file_sep>var express = require('express');
var router = express.Router();
var Enter = require('./controller/Enter.js');
var CreateUser = require('./controller/CreateUser.js');
module.exports = function(app) {
app.all("/",Enter.enter);
app.all("/register",CreateUser.createrNewUser);
}<file_sep>var indexApp = angular.module('indexApp', ['ngResource', 'ngRoute']);
/*
* routes for saindex.html
*/
indexApp.config(function($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateUrl: '/MainHtml/MainPage.html',
controller: 'MainController'
}).
when('/activity', {
templateUrl: '/MainHtml/activity.html',
controller: 'ActivityController'
}).
when('/download', {
templateUrl: '/MainHtml/download.html',
controller: 'DownloadController'
}).
when('/groupon', {
templateUrl: '/MainHtml/groupon.html',
controller: 'GrouponController'
}).
when('/school', {
templateUrl: '/MainHtml/school.html',
controller: 'SchoolController'
});
// configure html5 to get links working on jsfiddle
// $locationProvider.html5Mode(true);
console.log("initialize route");
});
indexApp.controller('IndexController', function($scope, $resource, $routeParams, $location) {
$scope.register_show = false;
$scope.login_show = false;
$scope.otherfuction_show = false;
$scope.feedback_show = false;
$scope.agree = true;
//注册验证中的密码相同检验
$scope.same_password=false;
/* 监视密码2的输入,如果输入和密码1的相同,则可以注册。
若不同,或者两个密码都为空,则不可注册。*/
// $scope.$watch("password_cf", function(newVal,oldVal,scope){
// if (newVal === oldVal){
// }
// else if(!$scope.password_cf){
// $scope.same_password=false;
// }
// else if($scope.password !== $scope.password_cf){
// $scope.same_password=false;
// }
// else if($scope.password === $scope.password_cf){
// $scope.same_password=true;
// }
// });
// /* 按监视密码2的方法监视密码1*/
// $scope.$watch("password", function(newVal,oldVal,scope){
// if (newVal === oldVal){
// }
// else if(!$scope.password){
// $scope.same_password=false;
// }
// else if($scope.password !== $scope.password_cf){
// $scope.same_password=false;
// }
// else if($scope.password === $scope.password_cf){
// $scope.same_password=true;
// }
// });
// $scope.register = function() {
// $resource("/register").get({
// nickname: $scope.nickname,
// email: $scope.email,
// password: $<PASSWORD>
// }, function(res) {
// $scope.reg_mess = res.mess;
// });
// }
});
indexApp.controller('MainController', function($scope, $resource, $routeParams, $location) {
});
indexApp.controller('ActivityController', function($scope, $resource, $routeParams, $location) {
});
indexApp.controller('DownloadController', function($scope, $resource, $routeParams, $location) {
});
indexApp.controller('GrouponController', function($scope, $resource, $routeParams, $location) {
});
indexApp.controller('SchoolController', function($scope, $resource, $routeParams, $location) {
});<file_sep>var UserModel = require("../../model/UserModel.js");
exports.createrNewUser = function(req, res) {
console.log(req.nickname);
var email = req.query.email;
var nickname = req.query.nickname;
var password = req.query.password;
UserModel.findUserByNickname(nickname,function(err, user){
if (user&&user.confirm) {
res.sendError("用户名重复");
}
else if (err) {
res.sendError("系统繁忙,数据库错误");
}
else{
UserModel.findUserByEmail(email,function(err,user){
if (user&&user.confirm) {
res.sendError("邮箱重复");
}
else if (err) {
res.sendError("系统繁忙,数据库错误");
}
else {
UserModel.createSimpleUser(nickname, email, password,function(err,user){
if (err) {
res.sendError("注册失败");
}
else{
res.sendSuccess("感谢"+user.nickname+"的支持,注册成功");
}
});
}
});
}
});
}
|
0519cc9372cd8dc155fcf4dc4f6efa53f46a5df3
|
[
"JavaScript"
] | 4
|
JavaScript
|
1043099804/studyabroad_project
|
8eb01c09a3800beeec37d70eaf7adf89851bbb4c
|
cb7fa14d7109c1fd44b213e7a1686226404be58b
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
</head>
<body>
<div class="row" style="background-color: #ffffff; background-image: -webkit-radial-gradient(#fafafa, #ffffff); background-image: radial-gradient(#fafafa, #ffffff); background-repeat: no-repeat; background-repeat: no-repeat; background-position: center center; margin-bottom: 0;">
<div class="section">
<div class="row" style="width: 85%;">
<img src="img/logo-benavides.gif" style="float: left;" />
<h4 class="indigo-text" style="float: left; padding-left: 20px; padding-top: 5px;">Traffic manager</h4>
</div>
</div>
<div class="section center-align" id="panel1">
<br class="hide-on-small-only" />
<a href="admin.php" class="btn-large waves-effect red darken-2">Traffic Manager Web<i class="material-icons right">language</i></a>
<p>Incluye el <strong>monitor de incidencias</strong>, centros de distribución y administración en general</p>
<p class="hide-on-small-only"> </p>
</div>
<div class="divider" style="margin-left: 5%; margin-right: 5%;"></div>
<div class="section center-align" id="panel2">
<div class="row" style="width: 90%;">
<div class="col s12 m3">
<i class="material-icons medium blue-text text-blue darken-1">supervisor_account</i><br>
<a href="supervisor.php" class="btn-large waves-effect waves-light blue darken-1">Supervisor <i class="material-icons right">phone_android</i></a>
<p class="caption">Persona que se encuentra en piso, recibe las notificaciones de los incidentes y puede remediar y/o cerrar el incidente.</p>
</div>
<div class="col s12 m3">
<i class="material-icons medium indigo-text">open_with</i><br>
<a href="cd.php" class="btn-large waves-effect waves-light blue darken-4">Centro Distr. <i class="material-icons right">phone_android</i></a>
<p>Da de alta el paquete al crossdoc.<br><br>Le da entrada al producto e inicia su actividad dentro de Base de datos.</p>
</div>
<div class="col s12 m3">
<i class="material-icons medium indigo-text">directions_bus</i><br>
<a href="transportista.php" class="btn-large waves-effect waves-light green accent-4">Transportista <i class="material-icons right">phone_android</i></a>
<p>Captura incidencias y recibe notificacion de acciones a tomar.</p>
</div>
<div class="col s12 m3">
<i class="material-icons medium indigo-text">store</i><br>
<a href="sucursal.php" class="btn-large waves-effect waves-light blue darken-4">Sucursal <i class="material-icons right">phone_android</i></a>
<p>Persona que revisa en sucursal/tienda (checkout) y confirma de recibido.<br><br>Finaliza actividad en Base de datos</p>
</div>
</div>
<p class="hide-on-small-only"> </p>
<p> </p>
<p> </p>
<p> </p>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function(){
$('.parallax').parallax();
});
</script>
</body>
</html><file_sep><?php
$navbu = false;
$bus = [];
$pos = 0;
if (isset($_GET["bu"])) {
$bus = ["Oxxo", "Immex", "Oxxo Gas", "Oxxo Colombia"];
$pos = intval($_GET["bu"]);
if (($pos < 0) || ($pos > count($bus))) {
header("Location: home.php");
}
} else { header("Location: home.php"); }
$loc = explode("/", $_SERVER["SCRIPT_NAME"]);
$loc = $loc[count($loc)-1];
?>
<nav class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="home.php">MoBOX</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="home.php"><?= $bus[$pos -1]; ?></a>
</li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group collapse navbar-collapse" style="color: #fff; float: left; padding-top: 10px;">
Bienvenido <u><NAME></u>
</div>
<button type="button" class="btn btn-danger" onclick="window.location.href = 'login.php';">Salir</button>
</form>
</div>
</div>
</nav>
<div style="background-color: #FFCC00; background-image: -webkit-linear-gradient(#FFCC00,#E8B900); background-image: linear-gradient(#FFCC00,#E8B900); background-repeat: no-repeat; margin-bottom: 10px; padding-top: 10px;">
<div class="container">
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" <?php if(strpos($loc, "indicators1") !== false) { ?>class="active"<?php } ?>><a href="indicators1.php?bu=<?= $pos ?>">Cierre Mensual</a></li>
<li role="presentation" <?php if(strpos($loc, "indicators2") !== false) { ?>class="active"<?php } ?>><a href="indicators2.php?bu=<?= $pos ?>">TOPs</a></li>
<li role="presentation" <?php if(strpos($loc, "indicators3") !== false) { ?>class="active"<?php } ?>><a href="indicators3.php?bu=<?= $pos ?>">IT</a></li>
<li role="presentation" <?php if(strpos($loc, "indicators4") !== false) { ?>class="active"<?php } ?>><a href="indicators4.php?bu=<?= $pos ?>">Service Delivery</a></li>
</ul>
</div>
</div>
<file_sep><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MoBOX</title>
<?php include("inc/meta-head.php"); ?>
<?php include("inc/scripts.php"); ?>
<?php include("inc/styles.php"); ?>
<style>
/*#contenido1, #contenido2, #contenido3 { display: none; }*/
.nav-justified a:hover {
font-weight: bold;
}
</style>
<script type="text/javascript">
function random(){
return Math.round(Math.random()*100);
}
</script>
</head>
<body>
<?php include("inc/navbar.php"); ?>
<div class="container">
<div class="row">
<div class="col-xs-10 col-md-6">
<table>
<tr>
<td>Avance del Cierre del Mes de </td>
<td nowrap="nowrap">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Enero <span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#" onclick="loadCharts();">Enero</a></li>
<li><a href="#" onclick="loadCharts();">Febrero</a></li>
<li><a href="#" onclick="loadCharts();">Marzo</a></li>
</ul>
</div>
</td>
<td>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
2016 <span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#" onclick="loadCharts();">2016</a></li>
<li><a href="#" onclick="loadCharts();">2015</a></li>
<li><a href="#" onclick="loadCharts();">2014</a></li>
</ul>
</div>
</td>
</tr>
</table>
</div>
<div class="col-xs-2 col-md-6 text-right">
<p>
<button type="button" class="btn btn-default" aria-label="Right Align" onclick="sendEmail();">
<span class="glyphicon glyphicon-share" aria-hidden="true"></span>
<span class="hidden-sm">Compartir</span>
</button>
<button type="button" class="btn btn-default" aria-label="Right Align">
<span class="glyphicon glyphicon-download" aria-hidden="true"></span>
<span class="hidden-sm">Descargar</span>
</button>
</p>
</div>
</div>
<div class="row">
<div class="col-md-5">
<h3 class="text-center"><NAME> <script type="text/javascript">document.write(random());</script> %</h3>
<canvas id="modular-doughnut1" style="height: 300px;"></canvas>
<div id="js-legend" class="chart-legend"></div>
<ul class="doughnut-legend">
<li><span style="background-color:#5B90BF"></span>Tota plazas: <span style="font-size: 20px;" id="rand1"></span></li>
<li><span style="background-color:#96b5b4"></span>Plazas cerradas: <span style="font-size: 20px;" id="rand2"></span></li>
<li><span style="background-color:#b48ead"></span>Plazas abiertas: <span style="font-size: 20px;" id="rand3"></span></li>
</ul>
</div>
<div class="col-md-7">
<table class="table table-striped table-bordered">
<tr>
<td>10MON</td>
<td>10RST</td>
<td>10SIS</td>
<td rowspan="5" style="background: #fff;">
<canvas id="myChart" height="250px" style="height: 250px;"></canvas>
</td>
</tr>
<tr>
<td>10ABC</td>
<td>10AJL</td>
<td>10MTY</td>
</tr>
<tr>
<td>10CTL</td>
<td>10UKL</td>
<td>10KSR</td>
</tr>
<tr>
<td>10PHC</td>
<td>10IKL</td>
<td>10AFR</td>
</tr>
<tr>
<td>10JIT</td>
<td></td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<script src="js/bootstrap.js"></script>
<script type="text/javascript">
/*
$(document).ready(function() {
$("#contenido1").css("display", "none");
$("#contenido2").css("display", "none");
$("#contenido3").css("display", "none");
$("#contenido1").fadeIn(1000);
$("#contenido2").fadeIn(1000);
$("#contenido3").fadeIn(1000);
});
*/
</script>
<script type="text/javascript">
function loadCharts() {
num1 = random(); num2 = random(); num3 = random();
document.getElementById('rand1').innerText = num1;
document.getElementById('rand2').innerText = num2;
document.getElementById('rand3').innerText = num3;
var canvas = document.getElementById('modular-doughnut1');
helpers = Chart.helpers;
var moduleData = [
{ value: num1,
color: "#f30",
highlight: "#f00",
label: "Total plazas"
},
{ value: num2,
color: "#f60",
highlight: "#f00",
label: "Plazas cerradas"
},
{ value: num3,
color: "#f90",
highlight: "#f00",
label: "Plazas abiertas"
}
];
var data = {
labels: ["10MON", "10RST", "10SIS", "10ABC", "10AJL", "10MTY", "10CTL"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 90, 81, 56, 55, 40]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 96, 27, 100]
}
]
};
var moduleDoughnut = new Chart(canvas.getContext('2d')).Pie(moduleData, {
tooltipTemplate : "<%if (label){%><%=label%>: <%}%><%= value %>", animation: true
});
helpers.addEvent(canvas, 'click', function(evt){
moduleDoughnut.options.animation = true;
moduleDoughnut.options.onAnimationComplete = function(){
this.showTooltip(this.activeElements, true);
};
var parts = moduleDoughnut.getSegmentsAtEvent(evt);
helpers.each(parts, function(bar){
//bar.value = Math.max(random(), 5);
});
if (parts.length > 0){
//sendEmail();
}
});
var ctx = document.getElementById("myChart").getContext("2d");
var options = {};
var myLineChart = new Chart(ctx).Radar(data, options);
}
function sendEmail() {
var r = prompt("Ingrese el email del destinatario para enviar éste dato");
alert("Email enviado a: " + r + "\r\n\r\nGracias.");
}
(function(){
Chart.defaults.global.responsive = true;
loadCharts();
})();
</script>
</body>
</html><file_sep><!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Midsa - Online Store</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/carousel.css" rel="stylesheet">
<link href="css/bootstrap-theme.css" rel="stylesheet">
</head>
<body>
<div class="container">
<?php include 'inc/header.php'; ?>
<div class="row" style="padding-top: 120px;">
<div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar">
<div class="list-group">
<a href="#" class="list-group-item">Catálogo</a>
<a href="nylon.php" class="list-group-item ">Nylon</a>
<a href="poliprop" class="list-group-item active">Polipropileno</a>
<div style="margin: 10px;">PP Homopolímero</div>
<div style="margin: 10px;">Nylamid XL</div>
<a href="polietileno" class="list-group-item">Polietileno / HDPE</a>
<a href="fenolicos" class="list-group-item">Fenolicos / Micartas</a>
<a href="acrilico" class="list-group-item">Acrilico</a>
<a href="cortinas" class="list-group-item">Cortinas Hawaianas</a>
<a href="policar" class="list-group-item">Policarbonato</a>
<a href="ptfe" class="list-group-item">Barras y Placas PTFE</a>
<a href="antiadherentes" class="list-group-item">Telas Antiadherentes</a>
<a href="acetal" class="list-group-item">Acetal (POM)</a>
<a href="sanalite" class="list-group-item">Sanalite</a>
<a href="pvc" class="list-group-item">PVC</a>
<a href="antiestaticos" class="list-group-item">Antiestaticos</a>
<a href="especiales" class="list-group-item">Especializados</a>
<a href="stabilit" class="list-group-item">Liner Panel (Recubrimientos de pared)</a>
</div>
</div>
<div class="col-xs-12 col-sm-9">
<p class="pull-right visible-xs">
<button type="button" class="btn btn-primary btn-xs"
data-toggle="offcanvas">Toggle nav</button>
</p>
<div class="jumbotron" style="background: #a249cf;">
<h1>Polipropileno</h1>
<p>frece una relación de resistencia vs peso muy favorable. Y resistencia química excelente para el uso en ambientes altamente corrosivos.
El Polipropileno Homopolímero natural es fácil de manejar para fabricar tanques y equipos de proceso</p>
</div>
<div class="row">
<div class="col-xs-6 col-lg-4">
<h2>PP Homopolímero</h2>
<p>Utilizado también como en el
recubrimiento protector de metales en procesos químicos corrosivos. Por su excelente comformabilidad y la consistencia del material en el
termoformado; El Poliporpileno ya es un estándar en la industria de prótesis y órtesis.</p>
<p>
<a class="btn btn-default" href="#" role="button">Agregar »</a>
</p>
</div>
<div class="col-xs-6 col-lg-4">
<h2>PP Homopolímero</h2>
<p>Ofrece la misma resistencia química excelente de PP homopolímero, con el beneficio añadido de mejor resistencia a la fisuración bajo
tensión a temperaturas bajas y ser más flexible.</p>
<p>
<a class="btn btn-default" href="#" role="button">Agregar »</a>
</p>
</div>
</div>
</div>
</div>
<?php include 'inc/footer.php';?>
</div>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
<style type="text/css">
td, th {
padding: 5px;
border: 1px solid #ccc;
}
th {
text-align: center;
text-transform: uppercase;
background-color: #009688;
color: #fff;
}
</style>
</head>
<body>
<?php include 'inc/nav-admin.php'; ?>
<div class="container" style="width: 85%;">
<div class="row">
<div class="col s12">
<p>
<a href="admin.php">Administración</a>
<i class="material-icons grey-text" style="vertical-align: bottom;">keyboard_arrow_right</i>
Catálogo de Sucursales
</p>
<h5>Catálogo de Sucursales</h5>
<table class="table bordered striped">
<tr>
<th>ID</th>
<th>Sucursal</th>
<th>Región</th>
<th>Tipo</th>
<th>24 Horas</th>
<th>Consultorio</th>
</tr>
<tr>
<td>1</td>
<td>CEL</td>
<td>NORTE</td>
<td>CEL</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>2</td>
<td>CORPORATIVO</td>
<td>NORTE</td>
<td>CORP</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>3</td>
<td>Barragán 2</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>4</td>
<td>Calzada del Valle</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>5</td>
<td>Centrika</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>6</td>
<td>Citadina</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>7</td>
<td>EL REGIO</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>8</td>
<td>Francisco de Quevedo</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>9</td>
<td>GALERÍAS MONTERREY</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>10</td>
<td>Garza Sada</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>11</td>
<td>Guadalupe Centro</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>12</td>
<td>HACIENDA DEL SOL</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>13</td>
<td><NAME></td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>14</td>
<td>MI PLAZA LOS ÁNGELES</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>15</td>
<td>MISIÓN ANÁHUAC</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>16</td>
<td>OMA MTY – TC</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>17</td>
<td>PASEO LAS AMÉRICAS</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>18</td>
<td>PLAZA BOLIVAR</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>19</td>
<td>PLAZA QU</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>20</td>
<td>PLAZA REMAX</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>21</td>
<td>PROVEE MUGUERZA</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>22</td>
<td>PROVEE OCA</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>23</td>
<td>Paseo La Fe</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>24</td>
<td>Plaza G3</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>25</td>
<td>QUINTA MONTECARLO</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>26</td>
<td>Real del Valle</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>27</td>
<td>SUC. 20 DE NOVIEMBRE ( N.L. )</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>28</td>
<td>SUC. ABEDUL</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>29</td>
<td>SUC. ALFONSO REYES</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>30</td>
<td>SUC. AMAZONAS</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>31</td>
<td>SUC. AMÉRICAS (Cd. Guadalupe)</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>32</td>
<td>SUC. ANILLO VIAL</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>33</td>
<td>SUC. ANÁHUAC</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>34</td>
<td>SUC. APODACA</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>35</td>
<td>SUC. ARRAMBERRI</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>36</td>
<td>SUC. ARTEAGA</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>37</td>
<td>SUC. ARTURO B. DE LA GARZA</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>38</td>
<td>SUC. ASTROS</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>39</td>
<td>SUC. AZTLÁN (Monterrey)</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>40</td>
<td>SUC. AZTLÁN METRO</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>41</td>
<td>SUC. BLVD ACAPULCO</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>42</td>
<td>SUC. BOSQUES DEL PTE.</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>43</td>
<td>SUC. CADEREYTA</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>44</td>
<td>SUC. CALIFORNIA (Escobedo)</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>45</td>
<td>SUC. <NAME></td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>46</td>
<td>SUC. CARRETERA MONTEMORELOS</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>47</td>
<td>SUC. CASA BLANCA</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>48</td>
<td>SUC. CENTRO DE MTY</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>49</td>
<td>SUC. CERRALVO</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>50</td>
<td>SUC. CERRO MITRAS</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>51</td>
<td>SUC. CHAPULTEPEC (Monterrey)</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>52</td>
<td>SUC. CHINA</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>53</td>
<td>SUC. CHIPINQUE</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>54</td>
<td>SUC. CIENEGA DE FLORES</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>55</td>
<td>SUC. CIMA CUMBRES</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>56</td>
<td>SUC. CLOUTIER</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>57</td>
<td>SUC. COLINAS DE SAN JERÓNIMO</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>58</td>
<td>SUC. COLINAS DEL SOL</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>59</td>
<td>SUC. COLOSIO</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>60</td>
<td>SUC. CONDOMINIOS</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>61</td>
<td>SUC. CONSTITUYENTES</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>62</td>
<td>SUC. CONTRY</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>63</td>
<td>SUC. COR<NAME></td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>64</td>
<td>SUC. CRECIA CAMINO AL MEZQUITAL</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>65</td>
<td>SUC. CUAHUTÉMOC METRO</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>66</td>
<td>SUC. CUMBRES</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>67</td>
<td>SUC. CUMBRES DE SAN ÁNGEL </td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>68</td>
<td>SUC. DEL MAESTRO</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>69</td>
<td>SUC. DOS RÍOS</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>70</td>
<td>SUC. DÍAZ DE BERLANGA</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>71</td>
<td>SUC. E. SEXTA</td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>72</td>
<td>SUC. EL CERCADO</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>73</td>
<td>SUC. ELOY CAVAZOS</td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>74</td>
<td>SUC. ESCOBEDO</td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>75</td>
<td>SUC. EXPOSICIÓN</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>76</td>
<td>SUC. FERROCARRILERA</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>77</td>
<td>SUC. <NAME></td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>78</td>
<td>SUC. GALEANA (Nuevo León)</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>79</td>
<td>SUC. GENERAL TERÁN</td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>80</td>
<td>SUC. <NAME></td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>81</td>
<td>SUC. <NAME></td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>82</td>
<td><NAME></td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>83</td>
<td>SUC. HACI<NAME> LERMAS</td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>84</td>
<td>SUC. HIDALGO (Nuevo León)</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>85</td>
<td>SUC. <NAME></td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>86</td>
<td>SUC. HOSPITAL</td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>87</td>
<td>SUC. H_CLÍNICA ROMA</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>88</td>
<td>SUC. H_Centro Médico Hidalgo</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>89</td>
<td>SUC. H_Centro Médico San Francisco</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>90</td>
<td>SUC. H_Del Paseo Muguerza</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>91</td>
<td>SUC. H_SAN MATEO ( 24 HORAS )</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>92</td>
<td>SUC. INDEPENDENCIA (Monterrey)</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>93</td>
<td>SUC. JUÁREZ</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>94</td>
<td>SUC. LA CIUDADELA</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>95</td>
<td>SUC. LA FLORESTA</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>96</td>
<td>SUC. LA FÉ</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>97</td>
<td>SUC. LA HUASTECA</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>98</td>
<td>SUC. LA PASTORA</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>99</td>
<td>SUC. LA PURÍSIMA</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>100</td>
<td>SUC. LAS HADAS</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>101</td>
<td>SUC. LAS MARGARITAS</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>102</td>
<td>SUC. LAS PALMAS (Apodaca)</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>103</td>
<td>SUC. LAS PUENTES</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>104</td>
<td>SUC. LAS TORRES</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>105</td>
<td>SUC. LEONES</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>106</td>
<td>SUC. LINARES</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>107</td>
<td>SUC. LINCOLN</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>108</td>
<td>SUC. LINDA VISTA</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>109</td>
<td>SUC. LOS ENCINOS</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>110</td>
<td>SUC. LOS PINOS</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>111</td>
<td>SUC. LÁZARO CÁRDENAS</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>112</td>
<td>SUC. LÓPEZ MATEOS</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>113</td>
<td>SUC. MADERO OTE</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>114</td>
<td>SUC. MAN<NAME> </td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>115</td>
<td>SUC. MANUEL ORDÓÑEZ</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>116</td>
<td>SUC. METRO GUADALUPE</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>117</td>
<td>SUC. METROPLEX</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>118</td>
<td>SUC. METROPOLITANO</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>119</td>
<td>SUC. MEZQUITAL</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>120</td>
<td>SUC. MIRASOL</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>121</td>
<td>SUC. MITRAS</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>122</td>
<td>SUC. MODERNA</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>123</td>
<td>SUC. MOISÉS SÁENZ</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>124</td>
<td>SUC. MONTE FALCO</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>125</td>
<td>SUC. MONTEMORELOS</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>126</td>
<td>SUC. <NAME></td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>127</td>
<td>SUC. MORENITA</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>128</td>
<td>SUC. <NAME></td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>129</td>
<td>SUC. MOVIMIENTO OBRERO</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>130</td>
<td>SUC. MÉXICO (Cd. Guadalupe)</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>131</td>
<td>SUC. NACIONAL (Allende)</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>132</td>
<td>SUC. NARANJO</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>133</td>
<td>SUC. NARANJOS</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>134</td>
<td>SUC. NARVARTE</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>135</td>
<td>SUC. NIÑOS HÉROES</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>136</td>
<td>SUC. NOGAL</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>137</td>
<td>SUC. NUEVA LAS PUENTES</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>138</td>
<td>SUC. OMA TA</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>139</td>
<td>SUC. OMA TB</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>140</td>
<td>SUC. ORDÓÑEZ ESCOBEDO</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>141</td>
<td>SUC. ORQUIDEA</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>142</td>
<td>SUC. PABLO LIVAS</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>143</td>
<td>SUC. PARQUES DE GUADALUPE </td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>144</td>
<td>SUC. PASEO DE LA AMISTAD</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>145</td>
<td>SUC. PASEO DEL NOGAL</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>146</td>
<td>SUC. PEDREGAL DE GUADALUPE</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>147</td>
<td>SUC. PEÑUELAS</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>148</td>
<td>SUC. PINO REAL</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>149</td>
<td>SUC. PLAZA GUADALUPE</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>150</td>
<td>SUC. PLAZA LOS NARANJOS</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>151</td>
<td>SUC. PLAZA SENDERO</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>152</td>
<td>SUC. PORFIRIO DÍAZ</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>153</td>
<td>SUC. POTRERO DE ANÁHUAC</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>154</td>
<td>SUC. PRADERAS</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>155</td>
<td>SUC. PRIVADAS DE LINDA VISTA</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>156</td>
<td>SUC. PUEBLO NUEVO (Apodaca)</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>157</td>
<td>SUC. RANGEL FRÍAS</td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>158</td>
<td>SUC. REAL SAN AGUSTÍN</td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>159</td>
<td>SUC. REPÚBLICA MEXICANA</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>160</td>
<td>SUC. RESIDENCIAL CUMBRES</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>161</td>
<td>SUC. RESIDENCIAL GUADALUPE</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>162</td>
<td>SUC. RESIDENCIAL LINCOLN</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>163</td>
<td>SUC. RESIDENCIAL SAN NICOLÁS</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>164</td>
<td>SUC. REVOLUCIÓN (Monterrey)</td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>165</td>
<td>SUC. REYNA</td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>166</td>
<td>SUC. RINCÓN DE HUINALÁ</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>167</td>
<td>SUC. RINCÓN DE SAN JERÓNIMO</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>168</td>
<td>SUC. RODR<NAME></td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>169</td>
<td>SUC. RUIZ CORTINES</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>170</td>
<td>SUC. RÍO PILÓN</td>
<td>SUR</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>171</td>
<td>SUC. S. FELIPE AZTECA O.F.M.</td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>172</td>
<td>SUC. S. FELIPE PADRE MIER O.F.M.</td>
<td>SUR</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>173</td>
<td>SUC. SABINAS (Nuevo León)</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>174</td>
<td>SUC. SABINAS CUAHUTÉMOC</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>175</td>
<td>SUC. SALINAS VICTORIA</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>176</td>
<td>SUC. SAN BERNABÉ</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>177</td>
<td>SUC. <NAME></td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>178</td>
<td>SUC. <NAME></td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>179</td>
<td>SUC. <NAME></td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>180</td>
<td>SUC. <NAME> (CADEREYTA)</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>181</td>
<td>SUC. SAN MIGUEL (Cd. Guadalupe)</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>182</td>
<td>SUC. SAN NICOLÁS</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>183</td>
<td>SUC. SAN PEDRO (Nuevo León)</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>184</td>
<td>SUC. SAN SEBASTIÁN</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>185</td>
<td>SUC. SANTA CATARINA</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>186</td>
<td>SUC. SANTA CECILIA</td>
<td>NORTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>187</td>
<td>SUC. SANTA MARÍA</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>188</td>
<td>SUC. SANTA ROSA</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>189</td>
<td>SUC. SATÉLITE (Monterrey)</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>190</td>
<td>SUC. SENDERO SAN ROQUE</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>191</td>
<td>SUC. SENDERO SUR</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>192</td>
<td>SUC. SOLIDARIDAD</td>
<td>NORTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>193</td>
<td>SUC. SUCHIATE</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>194</td>
<td>SUC. TECNOLÓGICO (Monterrey)</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>195</td>
<td>SUC. TELÉFONOS</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>196</td>
<td>SUC. TORRES DE SAN MIGUEL</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>197</td>
<td>SUC. U. MODELO</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>198</td>
<td>SUC. UNIDAD LABORAL</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>199</td>
<td>SUC. UNIVERSIDAD Y COLÓN</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>200</td>
<td>SUC. UNIÓN</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>201</td>
<td>SUC. URDIALES</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>202</td>
<td>SUC. VALLE ALTO</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>203</td>
<td>SUC. VALLE DE LAS PUENTES</td>
<td>NORESTE</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>204</td>
<td>SUC. VALLE DE LOS NOGALES</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>205</td>
<td>SUC. VALLE DORADO</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>206</td>
<td>SUC. VALLE OTE</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>207</td>
<td>SUC. VASCONCELOS</td>
<td>NORESTE</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>208</td>
<td>SUC. VICENTE GUERRERO</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>209</td>
<td>SUC. VILLA ALEGRE</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>SI</td>
</tr>
<tr>
<td>210</td>
<td>SUC. VILLA <NAME></td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>211</td>
<td>SUC. VIL<NAME></td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>212</td>
<td>SUC. VILLA SOL</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>213</td>
<td>SUC. VILLAGRÁN</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>214</td>
<td>SUC. VILLAS DEL MIRADOR</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>215</td>
<td>SUC. ZARAGOZA (Apodaca)</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>216</td>
<td>SUC. ZERTUCHE</td>
<td>CENTRO</td>
<td>SUC</td>
<td>SI</td>
<td>NO</td>
</tr>
<tr>
<td>217</td>
<td>SUC. ZUAZUA</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>218</td>
<td>SUC. ÁLAMOS</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>219</td>
<td>SUC. ÁLVAREZ</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>220</td>
<td><NAME></td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>SI</td>
</tr>
<tr>
<td>221</td>
<td>Satélite II</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
<tr>
<td>222</td>
<td>Villa Franca</td>
<td>CENTRO</td>
<td>SUC</td>
<td>NO</td>
<td>NO</td>
</tr>
</table>
<br>
<div class="center">
<a href="admin.php" class="btn waves-effect">Regresar</a>
</div>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".tab a").click(function() {
window.location.href = $(this).attr("href");
});
$(".button-collapse").sideNav();
$('.collapsible').collapsible();
});
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<script src="js/Chart.js"></script>
<script src="js/jquery-1.11.3.min.js"></script>
<?php include 'inc/styles.php'; ?>
<style type="text/css">
td, th {
padding: 0px;
border: 1px solid #ccc;
}
th {
text-align: center;
text-transform: uppercase;
background-color: #009688;
color: #fff;
}
.collapsible-body {
padding: 10px;
}
span.badge {
position: inherit;
}
span.badge.new {
font-size: 1rem;
}
div.collapsible-header.active {
background: #00bfa5;
color: #fff;
}
.card {
border-radius: 5px;
}
* {
font-size: 14px;
line-height: 20px;
}
</style>
</head>
<body class="blue-grey darken-5">
<?php include 'inc/nav-admin.php'; ?>
<div class="container" style="width: 95%;">
<div class="row">
<div class="col s6">
<div class="card">
<div class="card-content">
<div id="map" style="height: 400px;"></div>
<!--map name="estados" id="estados">
<area shape="rect" coords="598,401,600,403" alt="Image Map" style="outline:none;" title="Image Map" href="#" />
<area alt="Nuevo León: 8 incidentes nuevos" title="Nuevo León: 8 incidentes nuevos" href="#" shape="poly" coords="338,131,320,155,325,182,323,201,331,229,350,210,369,182" style="outline:none;" target="_self" />
<area alt="Jalisco: 14 incidentes nuevos" title="Jalisco: 14 incidentes nuevos" href="#" shape="poly" coords="309,251,281,263,280,237,260,240,255,269,237,280,257,310,290,303,303,282" style="outline:none;" target="_self" />
<area alt="Veracruz: 23 incidentes nuevos" title="Veracruz: 23 incidentes nuevos" href="#" shape="poly" coords="380,246,365,245,365,283,394,325,443,357,466,339,419,310" style="outline:none;" target="_self" />
</map-->
</div>
</div>
</div>
<div class="col s6">
<div class="card">
<div class="card-content">
<span class="card-title">
<ul class="collapsible" data-collapsible="accordion">
<li>
<div class="collapsible-header active">Región: NORTE</div>
<div class="collapsible-body">
<table class="table bordered striped">
<tr>
<th>ID</th>
<th>Sucursal</th>
<th>I
ncidentes</th>
</tr>
<tr>
<td>1</td>
<td>CEL</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>2</td>
<td>CORPORATIVO</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>3</td>
<td>Barragán 2</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>4</td>
<td>Calzada del Valle</td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td>5</td>
<td>Centrika</td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td>6</td>
<td>Citadina</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>7</td>
<td>EL REGIO</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>8</td>
<td>Francisco de Quevedo</td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td>9</td>
<td>GALERÍAS MONTERREY</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>10</td>
<td><NAME></td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td>11</td>
<td>Guadalupe Centro</td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td>12</td>
<td><NAME> SOL</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>13</td>
<td><NAME></td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>14</td>
<td>MI PLAZA LOS ÁNGELES</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>15</td>
<td>MISIÓN ANÁHUAC</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>16</td>
<td>OMA MTY – TC</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>17</td>
<td>PASEO LAS AMÉRICAS</td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td>18</td>
<td>PLAZA BOLIVAR</td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td>19</td>
<td>PLAZA QU</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>20</td>
<td>PLAZA REMAX</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
</table>
</div>
</li>
<li>
<div class="collapsible-header">Región: NORESTE</div>
<div class="collapsible-body">
<table class="table bordered striped">
<tr>
<td>21</td>
<td>PROVEE MUGUERZA</td>
<td>NORESTE</td>
<td>SUC</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>22</td>
<td>PROVEE OCA</td>
<td>NORESTE</td>
<td>SUC</td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>23</td>
<td>Paseo La Fe</td>
<td>NORESTE</td>
<td>SUC</td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>24</td>
<td>Plaza G3</td>
<td>NORESTE</td>
<td>SUC</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td>25</td>
<td>QUINTA MONTECARLO</td>
<td>NORESTE</td>
<td>SUC</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td>26</td>
<td>Real del Valle</td>
<td>NORESTE</td>
<td>SUC</td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>27</td>
<td>SUC. 20 DE NOVIEMBRE ( N.L. )</td>
<td>NORESTE</td>
<td>SUC</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>28</td>
<td>SUC. ABEDUL</td>
<td>NORESTE</td>
<td>SUC</td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>29</td>
<td>SUC. ALFONSO REYES</td>
<td>NORESTE</td>
<td>SUC</td>
<td><Span class="badge" data-badge-caption="incidentes">0</span></td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>30</td>
<td>SUC. AMAZONAS</td>
<td>NORESTE</td>
<td>SUC</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>31</td>
<td>SUC. AMÉRICAS (Cd. Guadalupe)</td>
<td>NORESTE</td>
<td>SUC</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>32</td>
<td>SUC. <NAME></td>
<td>NORESTE</td>
<td>SUC</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td>33</td>
<td>SUC. ANÁHUAC</td>
<td>NORESTE</td>
<td>SUC</td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
</table>
</div>
</li>
<li>
<div class="collapsible-header">Región: CENTRO</div>
<div class="collapsible-body">
</div>
</li>
<li>
<div class="collapsible-header">Región: SUR</div>
<div class="collapsible-body">
</div>
</li>
</ul>
</span>
</div>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col s12">
<div class="center">
<a href="admin.php" class="btn waves-effect">Regresar</a>
</div>
</div>
</div>
</div>
<script src="js/materialize.js"></script>
<script>
function initMap() {
var myLatLng = {lat: 25.6487281, lng: -100.443184};
// Create a map object and specify the DOM element for display.
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
scrollwheel: false,
zoom: 5
});
// Create a marker and set its position.
var marker = new google.maps.Marker({
map: map,
position: myLatLng,
title: 'Hello World!'
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<KEY>&callback=initMap" async defer></script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
</head>
<body class="grey lighten-4">
<?php include 'inc/nav-transportista.php'; ?>
<div class="container">
<br>
<h5>NOTIFICACIONES <span class="new badge red">4</span></h5>
<br>
<div class="card">
<div class="card-content">
<span class="card-title">Notificación 1 <i class="close material-icons right">close</i></span>
<p>El bulto <b>3</b> de la ruta APODACA va en otra ruta. No reportar</p>
</div>
</div>
<div class="card">
<div class="card-content">
<span class="card-title">Notificación 2 <i class="close material-icons right">close</i></span>
<p>Esta cerrado el Boulevard por reparación, toma la autopista.</p>
</div>
</div>
<div class="card">
<div class="card-content">
<span class="card-title">Notificación 3 <i class="close material-icons right">close</i></span>
<p>Faltó cargar un bulto de la ruta ESCOBEDO</p>
</div>
</div>
<div class="card">
<div class="card-content">
<span class="card-title">Notificación 4 <i class="close material-icons right">close</i></span>
<p>Favor de llevar vehículo a verificación</p>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$("i.close").click(function(){
$(this).parent().parent().parent().css("display", "none");
});
$(".button-collapse").sideNav();
});
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
<style type="text/css">
td, th {
padding: 5px;
border: 1px solid #ccc;
}
th {
text-align: center;
text-transform: uppercase;
background-color: #009688;
color: #fff;
}
</style>
</head>
<body>
<?php include 'inc/nav-admin.php'; ?>
<div class="container" style="width: 85%;">
<div class="row">
<div class="col s12">
<h5>Tracking de incidencias</h5>
<table class="table bordered striped">
<tr>
<th>Bulto</th>
<th>Transportista</th>
<th>Ruta</th>
<th>Ubicación</th>
<th>Estatus</th>
</tr>
<tr>
<td>1</td>
<td>rgarza</td>
<td>Sucursal APODACA</td>
<td>EMPACADO</td>
<td>SIN CARGAR</td>
</tr>
<tr>
<td>2</td>
<td>rgarza</td>
<td>Sucursal APODACA</td>
<td>EMPACADO</td>
<td>SIN CARGAR</td>
</tr>
<tr>
<td>3</td>
<td>fmarquez</td>
<td>Sucursal APODACA</td>
<td>ENTREGADO</td>
<td> ENTREGADO <i class="material-icons small right green-text">check_circle</i></td>
</tr>
<tr>
<td>4</td>
<td>rgarza</td>
<td>Sucursal ESCOBEDO</td>
<td>RECODIGO EN CROSSDOCK 2</td>
<td> EN TRÁNSITO</td>
</tr>
<tr>
<td>5</td>
<td>fmarquez</td>
<td>Sucursal APODACA</td>
<td>RECODIGO EN CROSSDOCK 1</td>
<td> EN TRÁNSITO</td>
</tr>
<tr>
<td>6</td>
<td>rgarza</td>
<td>Sucursal ESCOBEDO</td>
<td>EMPACADO</td>
<td>SIN CARGAR</td>
</tr>
<tr>
<td>7</td>
<td>rgarza</td>
<td>Sucursal ESCOBEDO</td>
<td>EMPACADO</td>
<td>SIN CARGAR</td>
</tr>
<tr>
<td>8</td>
<td>rgarza</td>
<td>Sucursal APODACA</td>
<td>EMPACADO</td>
<td>SIN CARGAR</td>
</tr>
<tr>
<td>9</td>
<td>rgarza</td>
<td>Sucursal APODACA</td>
<td>RECODIGO EN CROSSDOCK 2</td>
<td> EN TRÁNSITO</td>
</tr>
<tr>
<td>10</td>
<td>rgarza</td>
<td>Sucursal APODACA</td>
<td>RECODIGO EN CROSSDOCK 2</td>
<td> EN TRÁNSITO</td>
</tr>
<tr>
<td>11</td>
<td>rgarza</td>
<td>Sucursal ESCOBEDO</td>
<td>RECODIGO EN CROSSDOCK 2</td>
<td> EN TRÁNSITO</td>
</tr>
<tr>
<td>12</td>
<td>fmarquez</td>
<td>Sucursal ESCOBEDO</td>
<td>ENTREGADO</td>
<td> ENTREGADO <i class="material-icons small right green-text">check_circle</i></td>
</tr>
</table>
<div class="center">
<a href="admin.php" class="btn waves-effect">Regresar</a>
</div>
</div>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".tab a").click(function() {
window.location.href = $(this).attr("href");
});
$(".button-collapse").sideNav();
$('.collapsible').collapsible();
});
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MoBOX - Home</title>
<?php include("inc/meta-head.php"); ?>
<?php include("inc/scripts.php"); ?>
<?php include("inc/styles.php"); ?>
</head>
<body>
<nav class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<span class="navbar-brand">MoBOX</span>
</div>
</nav>
<div class="container">
<h3>Seleccione su unidad de negocio</h3>
<div class="row">
<div class="col-sm-6 col-md-3" align="center">
<p><a href="indicators1.php?bu=1"><img src="images/logo_oxxo.jpg" class="img-responsive" alt="Oxxo" /></a></p>
</div>
<div class="col-sm-6 col-md-3" align="center">
<p><a href="indicators2.php?bu=2"><img src="images/logo_immex.jpg" class="img-responsive" alt="Immex" /></a></p>
</div>
<div class="col-sm-6 col-md-3" align="center">
<p><a href="indicators3.php?bu=3"><img src="images/logo_oxxogas.jpg" class="img-responsive" alt="Oxxo Gas" /></a></p>
</div>
<div class="col-sm-6 col-md-3" align="center">
<p><a href="indicators4.php?bu=4"><img src="images/logo_oxxocolombia.jpg" class="img-responsive" alt="Oxxo Colombia" /></a></p>
</div>
</div>
</div>
<script src="js/bootstrap.js"></script>
</body>
</html><file_sep>var output;
var websocket;
function WebSocketSupport()
{
if (browserSupportsWebSockets() === false) {
document.getElementById("ws_support").innerHTML = "<h2>Sorry! Your web browser does not supports web sockets</h2>";
var element = document.getElementById("wrapper");
element.parentNode.removeChild(element);
return;
}
output = document.getElementById("chatbox");
websocket = new WebSocket('ws:172.16.31.10:999');
websocket.onopen = function(e) {
//writeToScreen("You have have successfully connected to the server");
};
websocket.onmessage = function(e) {
onMessage(e)
};
websocket.onerror = function(e) {
onError(e)
};
}
function onMessage(e) {
Materialize.toast('Nuevo incidente <i class="material-icons left">warning</i>', 3000);
var d = new Date();
var n = d.getMilliseconds();
switch(n%3) {
case 0: console.log("1"); $("#incidents").append('<a href="#" class="collection-item avatar"><i class="material-icons circle red" id="incident1-icon">warning</i><span class="title">Incidente 133</span><p><b>Sucursal ESCOBEDO</b><br>Ruta no corresponde al bulto...</p><span class="secondary-content" id="incident1-status"><b>REVISAR</b></span></a>');
break;
case 1: console.log("2"); $("#incidents").append('<a href="#" class="collection-item avatar"><i class="material-icons circle red" id="incident1-icon">warning</i><span class="title">Incidente 024</span><p><b>Sucursal APODACA</b><br>Bulto esta golpeado...</p><span class="secondary-content" id="incident1-status"><b>REVISAR</b></span></a>');
break;
case 2: console.log("3"); $("#incidents").append('<a href="#" class="collection-item avatar"><i class="material-icons circle red" id="incident1-icon">warning</i><span class="title">Incidente 015</span><p><b>Sucursal AEROPUERTO</b><br>Bulto no corresponde...</p><span class="secondary-content" id="incident1-status"><b>REVISAR</b></span></a>');
break;
}
//writeToScreen('<span style="color: blue;"> ' + e.data + '</span>');
}
function onError(e) {
//writeToScreen('<span style="color: red;">ERROR:</span> ' + e.data);
}
function doSend(message) {
var validationMsg = userInputSupplied();
if (validationMsg !== '') {
alert(validationMsg);
return;
}
var chatname = document.getElementById('chatname').value;
document.getElementById('msg').value = "";
document.getElementById('msg').focus();
var msg = '@<b>' + chatname + '</b>: ' + message;
websocket.send(msg);
//writeToScreen(msg);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
function userInputSupplied() {
var chatname = document.getElementById('chatname').value;
var msg = document.getElementById('msg').value;
if (chatname === '') {
return 'Please enter your username';
} else if (msg === '') {
return 'Please the message to send';
} else {
return '';
}
}
function browserSupportsWebSockets() {
if ("WebSocket" in window)
{
return true;
}
else
{
return false;
}
}
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Indautosoft - demos</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css" />
<script type="text/javascript" src="js/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<style type="text/css">
@import url(https://fonts.googleapis.com/css?family=Roboto:400);
body * { font-family: 'Roboto', Helvetica, sans-serif, Arial; }
html, body { height: 100%; }
body {
background-color: #fff;
background-image: -webkit-linear-gradient(#fff,#F9F7FC);
background-image: linear-gradient(#fff,#F9F7FC);
background-repeat: no-repeat;
}
h3 { font-weight: 700; }
a.list-group-item .title {
font-weight: bold;
font-size: 18px;
}
a.list-group-item:active .title,
a.list-group-item:hover .title {
color: #f30;
text-decoration: underline;
}
</style>
</head>
<body>
<div class="container">
<br/>
<div align="center">
<img src="img/logo-indautosoft.jpg" class="img-responsive" />
</div>
<h3 style="text-align: center;">Demos</h3>
<div class="col-sm-3"></div>
<div class="col-sm-6 list-group">
<a class="list-group-item" title="ir a" data-href2="benavides" href="http://52.38.17.98/benavides">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="title">Benavides</span><br/>
<span style="font-weight: 500;">Admnistrador de tráfico y captura de incidencias</span>
</a>
<a class="list-group-item" title="ir a" href="fyolo">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="title">fyolo</span><br/>
<span style="font-weight: 500;">Sitio web para compra online de publicidad.</span>
</a>
<a class="list-group-item" title="ir a" href="http://172.16.17.32:8080/midsa_ecommerce/">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="title">Midsa Ecommerce</span><br/>
<span style="font-weight: 500;">Ecommerce desarrollado con Spring 4, Hibernate, Bootstrap</span>
</a>
<a class="list-group-item" title="ir a" href="http://172.16.17.32:8080/pepsico_ecommerce/">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="title">PepsiCo Ecommerce</span><br/>
<span style="font-weight: 500;">Ecomerce mobile, diseño responsivo y geo-localización.</span>
</a>
<a class="list-group-item" title="ir a" href="detecta-color">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="title">Detección de color en imagen</span><br/>
<span style="font-weight: 500;">Aplicación para carga de imágenes vía mobile-web y detección de color.</span>
</a>
<a class="list-group-item" title="ir a" href="mobox-indicators">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="title">MoBox - Online indicators</span><br/>
<span style="font-weight: 500;">Indicadores web.</span>
</a>
</div>
<div class="col-sm-3"></div>
<!-- Lea el archivo README.md -->
</div>
<?php include_once("analyticstracking.php") ?>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Incident tracker - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
</head>
<body class="grey lighten-4">
<div class="navbar-fixed">
<?php include 'inc/nav-transportista.php'; ?>
</div>
<div class="row">
<div class="white grey-text text-darken-1" style="padding: 20px; border-bottom: 1px solid #ccc;">
<i class="material-icons grey-text" style="float: left;">date_range</i> <?= date("d / M / Y") ?>
<a href="#"><i class="material-icons grey-text" style="float: right; font-weight: 700;">keyboard_arrow_right</i></a>
<a href="#"><i class="material-icons grey-text" style="float: right; font-weight: 700;">keyboard_arrow_left</i></a>
</div>
</div>
<div class="container">
<a href="scan.php" class="btn btn-large waves-effect white light-blue-text text-darken-1" style="width: 100%;" id="btn-scan">
<i class="material-icons grey-text" style="float: left;">search</i> Escanear bulto
</a>
<br><br>
<div class="card">
<div class="card-content">
<span class="card-title activator grey-text text-darken-4" style="font-weight: 400;">Mis rutas <i class="material-icons right">more_vert</i></span>
<h5><a href="misrutas.php">12 rutas pendientes</a></h5>
<p>5 rutas ya entregadas</p>
</div>
</div>
<br>
<a href="capturar.php" class="btn btn-large waves-effect white light-blue-text text-darken-1" style="width: 100%;">
<i class="material-icons grey-text" style="float: left;">warning</i> Capturar incidencia
</a>
<br><br>
<a href="notificaciones.php" class="btn btn-large waves-effect white light-blue-text text-darken-1" style="width: 100%;">
<i class="material-icons grey-text" style="float: left;">announcement</i> Notificaciones <span class="new badge red">4</span>
</a>
<br><br>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".button-collapse").sideNav();
<?php if (isset($_REQUEST['send'])) { ?>
Materialize.toast('Bulto capturado <i class="material-icons right">done</i>', 3000);
<?php } ?>
<?php if (isset($_REQUEST['capture'])) { ?>
Materialize.toast('Incidencia capturada <i class="material-icons right">done</i>', 3000);
<?php } ?>
});
</script>
</body>
</html><file_sep><!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Midsa - Inicio de sesión</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/signin.css" rel="stylesheet">
</head>
<body>
<div class="container">
<?php include 'inc/header.php'; ?>
<br /> <br /> <br /> <br /> <br /> <br />
<form class="form-signin" action="home.php">
<h2 class="form-signin-heading">Inicio de sesión</h2>
<label for="inputEmail" class="sr-only">Dirección email</label> <input
type="email" id="inputEmail" class="form-control"
placeholder="Email address" required="" autofocus=""> <label
for="inputPassword" class="sr-only">Contraseña</label> <br> <input
type="password" id="inputPassword" class="form-control"
placeholder="<PASSWORD>" required="">
<div class="checkbox">
<label> <input type="checkbox" value="remember-me"> Recordarme
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Iniciar</button>
</form>
<br /> <br /> <br />
<?php include 'inc/footer.php';?>
</div>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
</head>
<body class="grey lighten-4">
<?php include 'inc/nav-supervisor.php'; ?>
<div class="container">
<div class="card">
<div class="card-content">
<span class="card-title activator" style="font-weight: 400;">Detalle del incidente <i class="material-icons right">more_vert</i></span>
<div class="row">
<div class="col s6">
<p>Sucursal: <b>APODACA</b></p>
<p>Transportista: <b>Francisco</b></p>
</div>
<div class="col s6">
<p>Incidente: <b>012</b></p>
<p>Día/hora: <b>17/08/2016 10:34 AM</b></p>
</div>
</div>
Comentarios: <br>
<textarea class="materialize-textarea grey lighten-2">
El bulto viene en condiciones sospechosas.
Observación: parece que se esta derramando un líquido, pero la caja viene en buen estado.</textarea>
<div class="center">
<a href="#" class="btn btn-large waves-effect activator">CERRAR incidente</a>
</div>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">Cerrar incidente<i class="material-icons right">close</i></span>
<div>
¿El incidente ha sido resuelto?
<p>
<input name="group1" type="radio" id="test1" />
<label for="test1">Si</label>
</p>
<p>
<input name="group1" type="radio" id="test2" />
<label for="test2">No</label>
</p>
</div>
<div class="input-field col s12">
<textarea class="materialize-textarea"></textarea>
<label>Motivo</label>
</div>
<div class="center">
<a href="supervisor.php?close=1" class="btn btn-large waves-effect">Enviar <i class="material-icons right">send</i></a>
</div>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".button-collapse").sideNav();
});
</script>
</body>
</html><file_sep><hr>
<footer>
<p class="pull-right">
© 2013 Midsa ®, Mar Industrial Distribuidora, S.A. de C.V<br /> <a
href="#">Privacidad y términos de uso</a>
</p>
<p>
Rayón 750 Sur. Col. Centro <br /> Monterrey N.L., C.P. 64000 México<br />
Tels. 01 (81) 8344 3061, 8344-4277
</p>
</footer><file_sep># Indautosoft demos
Repositorio de sitios web demos y aplicaciones para Indautosoft
Midsa Online Store - Tienda en línea para menudeo
MoBox Indicators - Aplicación de indicadores KPI para Mobile<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
</head>
<body class="grey lighten-4">
<?php include 'inc/nav-transportista.php'; ?>
<div class="container">
<div class="card">
<div class="card-content">
<span class="card-title" style="font-weight: 400;">MIS RUTAS</span>
</div>
<div class="card-action">
<p>Rutas para el día<h4>17/08/2016</h4></p>
<ul class="collection with-header">
<a href="misrutas2.php" class="collection-item active">Crossdock APODACA</a>
<a href="misrutas2.php" class="collection-item">Sucursal LA FE</a>
<a href="misrutas2.php" class="collection-item">Crossdock ESCOBEDO</a>
<a href="misrutas2.php" class="collection-item">Sucursal Periférico</a>
<a href="misrutas2.php" class="collection-item">Sucursal Centrika</a>
</ul>
<br>
<ul class="collection with-header">
<li class="collection-header">Rutas despachadas</li>
<li>
<p>
<input type="checkbox" id="test6" checked="checked" disabled="disabled">
<label for="test6" class="black-text">Tienda APODACA</label>
</p>
</li>
<li>
<p>
<input type="checkbox" id="test6" checked="checked" disabled="disabled">
<label for="test6" class="black-text">Sucursal Aeropuerto</label>
</p>
</li>
</ul>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".button-collapse").sideNav();
});
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MoBOX</title>
<?php include("inc/meta-head.php"); ?>
<?php include("inc/scripts.php"); ?>
<?php include("inc/styles.php"); ?>
</head>
<body>
<?php include("inc/navbar.php"); ?>
<div class="container">
<div class="row">
<div class="col-xs-10">
<table>
<tr>
<td>Avance del Cierre del Mes de </td>
<td nowrap="nowrap">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Enero <span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#" onclick="loadCharts();">Enero</a></li>
<li><a href="#" onclick="loadCharts();">Febrero</a></li>
<li><a href="#" onclick="loadCharts();">Marzo</a></li>
</ul>
</div>
</td>
<td>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
2016 <span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#" onclick="loadCharts();">2016</a></li>
<li><a href="#" onclick="loadCharts();">2015</a></li>
<li><a href="#" onclick="loadCharts();">2014</a></li>
</ul>
</div>
</td>
</tr>
</table>
</div>
</div>
<br/>
<div class="row" id="contenido2">
<div class="col-sm-6 col-md-4">
<div style="background: #7ebf34; color: #fff; padding: 5px; border-top-left-radius: 6px; border-top-right-radius: 6px;" align="center">
<a href="indicators1a.php?bu=<?=$_GET["bu"]?>" style="color: #fff;"><h4>Cierre GL</h4></a>
</div>
<div style="background: #8bd339; color: #fff; padding: 10px; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px;" align="center">
<a href="indicators1a.php?bu=<?=$_GET["bu"]?>" style="font-weight: bold; font-size: 28px; color: #fff; cursor: pointer;">98 %</a>
<canvas id="modular-doughnut1"></canvas>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div style="background: #7ebf34; color: #fff; padding: 5px; border-top-left-radius: 6px; border-top-right-radius: 6px;" align="center">
<h4>Cierre de Inventarios</h4>
</div>
<div style="background: #8bd339; color: #fff; padding: 10px; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px;" align="center">
<span style="font-weight: bold; font-size: 28px; color: #fff;">95.44 %</span>
<canvas id="modular-doughnut2"></canvas>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div style="background: #cd2525; color: #fff; padding: 5px; border-top-left-radius: 6px; border-top-right-radius: 6px;" align="center">
<h4>Finiquitos <span class="glyphicon glyphicon-warning-sign" aria-hidden="true"></span></h4>
</div>
<div style="background: #da3232; color: #fff; padding: 10px; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px;" align="center">
<span style="font-weight: bold; font-size: 28px; color: #fff;">90.22 %</span>
<canvas id="modular-doughnut3"></canvas>
</div>
</div>
</div>
<br/>
<div class="row" id="contenido3">
<div class="col-sm-6 col-md-4">
<div style="background: #7ebf34; color: #fff; padding: 5px; border-top-left-radius: 6px; border-top-right-radius: 6px;" align="center">
<h4>Usuarios Conectados</h4>
</div>
<div style="background: #8bd339; color: #fff; padding: 10px; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px;" align="center">
<span style="font-weight: bold; font-size: 28px; color: #fff;">400</span>
<canvas id="interactive-bar" style="cursor: default;"></canvas>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div style="background: #7ebf34; color: #fff; padding: 5px; border-top-left-radius: 6px; border-top-right-radius: 6px;" align="center">
<h4>Solicitudes por Hora</h4>
</div>
<div style="background: #8bd339; color: #fff; padding: 10px; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px;" align="center">
<span style="font-weight: bold; font-size: 28px; color: #fff;">300</span>
<canvas id="interactive-bar2" style="cursor: default;"></canvas>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div style="background: #7ebf34; color: #fff; padding: 5px; border-top-left-radius: 6px; border-top-right-radius: 6px;" align="center">
<h4>Pólizas</h4>
</div>
<div style="background: #8bd339; color: #fff; padding: 10px; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px;" align="center">
<span style="font-weight: bold; font-size: 28px; color: #fff;">5</a>
</div>
</div>
</div>
<p> </p>
</div>
<script type="text/javascript">
loadCharts = function() {
var data = [],
barsCount = 50,
labels = new Array(barsCount),
updateDelayMax = 500,
$id = function(id){
return document.getElementById(id);
},
random = function(max){ return Math.round(Math.random()*100)},
helpers = Chart.helpers;
Chart.defaults.global.responsive = true;
var moduleData1 = [
{ value: random(),
color: "#5b90bf",
highlight: "#369",
label: "<NAME>"
},
{ value: random(),
color: "#c7c7c7",
highlight: "#369",
label: "Previsto"
},
{ value: random(),
color: "#be40f3",
highlight: "#369",
label: "Otros"
}
];
var moduleData2 = [
{ value: random(),
color: "#5b90bf",
highlight: "#369",
label: "<NAME>"
},
{ value: random(),
color: "#c7c7c7",
highlight: "#369",
label: "Otros"
}
];
var moduleData3 = [
{ value: random(),
color: "#ffcc06",
highlight: "#fff606",
label: "Entregados"
},
{ value: random(),
color: "#88a0b9",
highlight: "#369",
label: "No entregados"
},
{ value: random(),
color: "#da81d5",
highlight: "#369",
label: "Otros"
}
];
var options = {
tooltipTemplate : "<%if (label){%><%=label%>: <%}%><%= value %> %",
segmentShowStroke : false,
animation: true
};
var canvas = $id('modular-doughnut1');
var moduleDoughnut = new Chart(canvas.getContext('2d')).Doughnut(moduleData1, options);
var canvas = $id('modular-doughnut2');
var moduleDoughnut = new Chart(canvas.getContext('2d')).Doughnut(moduleData2, options);
var canvas = $id('modular-doughnut3');
var moduleDoughnut = new Chart(canvas.getContext('2d')).Doughnut(moduleData3, options);
// Interative micro bar chart
var data1 = {
labels: ["Lun", "Mar", "Mie", "Jue", "Vie", "Sab", "Dom"],
datasets: [{
fillColor : "#f24d14",
highlightFill: "#f30",
data: [random(), random(), random(), random(), random(), random(), random()],
}]
};
var data2 = {
labels: ["01 AM", "02 AM", "03 AM", "04 AM", "05 AM", "06 AM", "07 AM", "08 AM", "09 AM", "10 AM", "11 AM", "12 AM"],
datasets: [
{
label: "My First dataset",
fillColor: "#4990d0",
strokeColor: "rgba(220,220,220,1)",
pointColor: "#fff",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
bezierCurve : false,
pointHighlightStroke: "rgba(220,220,220,1)",
data: [random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random()]
}]
};
var options = {
animation: true,
showScale: false,
barShowStroke: false,
tooltipXPadding: 10,
tooltipYPadding: 6,
tooltipFontSize: 18,
tooltipFontStyle: 'bold',
// Boolean - If we want to override with a hard coded scale
scaleOverride: true,
// ** Required if scaleOverride is true **
// Number - The number of steps in a hard coded scale
scaleSteps: 2,
// Number - The value jump in the hard coded scale
scaleStepWidth: 50,
// Number - The scale starting value
scaleStartValue: 0,
bezierCurve : false
};
var canvas = $id('interactive-bar');
var microBar = new Chart(canvas.getContext('2d')).Bar(data1, options);
helpers.addEvent(canvas, 'mousemove', function(evt){
var bars = microBar.getBarsAtEvent(evt);
if (bars.length > 0){
canvas.style.cursor = "pointer";
}
else {
canvas.style.cursor = "default";
}
});
helpers.addEvent(canvas, 'click', function(evt){
microBar.options.animation = true;
microBar.options.onAnimationComplete = function(){
this.showTooltip(this.activeElements, true);
};
var bars = microBar.getBarsAtEvent(evt);
helpers.each(bars, function(bar){
bar.value = Math.max(random(), 5);
});
if (bars.length > 0){
microBar.update();
}
});
var canvas = $id('interactive-bar2');
var linechart = new Chart(canvas.getContext('2d')).Line(data2, options);
helpers.addEvent(canvas, 'mousemove', function(evt){
var bars =linechart.getBarsAtEvent(evt);
if (bars.length > 0){
canvas.style.cursor = "pointer";
}
else {
canvas.style.cursor = "default";
}
});
};
(function(){
loadCharts();
})();
</script>
<script src="js/bootstrap.js"></script>
</body>
</html><file_sep><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/png" href="favicon.ico">
<title>Fyolo | Publicidad</title>
<!-- CSS Files -->
<link href="css/bootstrap.css" rel="stylesheet" />
<!--link href="css/rubick_pres.css" rel="stylesheet"/-->
<link href="css/material-bootstrap-wizard.css" rel="stylesheet" />
<!-- Fonts and icons -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" />
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:400,700|Material+Icons" />
<link href="css/fonts/Rubik-Fonts.css" rel="stylesheet" />
<link href="css/demo.css" rel="stylesheet" />
</head>
<body>
<div class="image-container set-full-height">
<!-- Big container -->
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<!-- Wizard container -->
<div class="wizard-container">
<div class="card wizard-card" data-color="red" id="wizard">
<form action="" method="">
<!-- You can switch " data-color="blue" " with one of the next bright colors: "green", "orange", "red", "purple" -->
<div class="wizard-header">
<h3 class="wizard-title">Contrata</h3>
<h5>This information will let us know more about you.</h5>
</div>
<div class="wizard-navigation">
<ul>
<li><a href="#details" data-toggle="tab">REGÍSTRATE O INGRESA</a></li>
<li><a href="#captain" data-toggle="tab">ELIGE UN PAQUETE</a></li>
<li><a href="#description" data-toggle="tab">ORDENA</a></li>
</ul>
</div>
<div class="tab-content">
<div class="tab-pane" id="details">
<div class="row">
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">email</i>
</span>
<div class="form-group label-floating">
<label class="control-label">Your Email</label>
<input name="name" type="text" class="form-control">
</div>
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">lock_outline</i>
</span>
<div class="form-group label-floating">
<label class="control-label">Your Password</label>
<input name="name2" type="<PASSWORD>" class="form-control">
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group label-floating">
<label class="control-label">Country</label>
<select class="form-control">
<option disabled="" selected=""></option>
<option value="Afghanistan"> Afghanistan </option>
<option value="Albania"> Albania </option>
<option value="Algeria"> Algeria </option>
<option value="American Samoa"> American Samoa </option>
<option value="Andorra"> Andorra </option>
<option value="Angola"> Angola </option>
<option value="Anguilla"> Anguilla </option>
<option value="Antarctica"> Antarctica </option>
<option value="...">...</option>
</select>
</div>
<div class="form-group label-floating">
<label class="control-label">Daily Budget</label>
<select class="form-control">
<option disabled="" selected=""></option>
<option value="Afghanistan"> < $100 </option>
<option value="Albania"> $100 - $499 </option>
<option value="Algeria"> $499 - $999 </option>
<option value="American Samoa"> $999+ </option>
</select>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="captain">
<h4 class="info-text">What type of room would you want? </h4>
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="col-sm-4">
<div class="choice" data-toggle="wizard-radio" rel="tooltip" title="This is good if you travel alone.">
<input type="radio" name="job" value="Design">
<div class="icon">
<i class="material-icons">weekend</i>
</div>
<h6>Single</h6>
</div>
</div>
<div class="col-sm-4">
<div class="choice" data-toggle="wizard-radio" rel="tooltip" title="Select this room if you're traveling with your family.">
<input type="radio" name="job" value="Code">
<div class="icon">
<i class="material-icons">home</i>
</div>
<h6>Family</h6>
</div>
</div>
<div class="col-sm-4">
<div class="choice" data-toggle="wizard-radio" rel="tooltip" title="Select this option if you are coming with your team.">
<input type="radio" name="job" value="Code">
<div class="icon">
<i class="material-icons">business</i>
</div>
<h6>Business</h6>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="description">
<div class="row">
<h4 class="info-text"> Drop us a small description.</h4>
<div class="col-sm-6 col-sm-offset-1">
<div class="form-group">
<label>Room description</label>
<textarea class="form-control" placeholder="" rows="6"></textarea>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label class="control-label">Example</label>
<p class="description">"The room really nice name is recognized as being a really awesome room. We use it every sunday when we go fishing and we catch a lot. It has some kind of magic shield around it."</p>
</div>
</div>
</div>
</div>
</div>
<div class="wizard-footer">
<div class="pull-right">
<input type='button' class='btn btn-next btn-fill btn-danger btn-wd' name="SIGUIENTE" value="SIGUIENTE"/>
<input type='button' class='btn btn-finish btn-fill btn-danger btn-wd' name="TERMINAR" value="TERMINAR" />
</div>
<div class="pull-left">
<input type='button' class='btn btn-previous btn-fill btn-default btn-wd' name="ANTERIOR" value="ANTERIOR" />
</div>
<div class="clearfix"></div>
</div>
</form>
</div>
</div> <!-- wizard container -->
</div>
</div> <!-- row -->
</div>
</div>
<!-- Core JS Files -->
<script src="js/jquery-2.2.4.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script src="js/jquery.bootstrap.js" type="text/javascript"></script>
<!-- Plugin for the Wizard -->
<script src="js/demo.js" type="text/javascript"></script>
<script src="js/material-bootstrap-wizard.js" type="text/javascript"></script>
<!-- More information about jquery.validate here: http://jqueryvalidation.org/ -->
<script src="js/jquery.validate.min.js" type="text/javascript"></script>
<?php include_once("../analyticstracking.php") ?>
</body>
</html><file_sep><!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Midsa - Online Store</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/carousel.css" rel="stylesheet">
<link href="css/bootstrap-theme.css" rel="stylesheet">
</head>
<body>
<div class="container">
<?php include 'inc/header.php'; ?>
<div class="row" style="padding-top: 120px;">
<div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar">
<div class="list-group">
<a href="#" class="list-group-item">Catálogo</a> <a href="#"
class="list-group-item active">Nylon</a>
<div style="margin: 10px;">Nylamid M</div>
<div style="margin: 10px;">Nylamid XL</div>
<div style="margin: 10px;">Nylamid 901</div>
<div style="margin: 10px;">Nylamid SL</div>
<a href="polipropileno.php" class="list-group-item">Polipropileno</a>
<a href="polietileno" class="list-group-item">Polietileno / HDPE</a>
<a href="fenolicos" class="list-group-item">Fenolicos / Micartas</a>
<a href="acrilico" class="list-group-item">Acrilico</a>
<a href="cortinas" class="list-group-item">Cortinas Hawaianas</a>
<a href="policar" class="list-group-item">Policarbonato</a>
<a href="ptfe" class="list-group-item">Barras y Placas PTFE</a>
<a href="antiadherentes" class="list-group-item">Telas Antiadherentes</a>
<a href="acetal" class="list-group-item">Acetal (POM)</a>
<a href="sanalite" class="list-group-item">Sanalite</a>
<a href="pvc" class="list-group-item">PVC</a>
<a href="antiestaticos" class="list-group-item">Antiestaticos</a>
<a href="especiales" class="list-group-item">Especializados</a>
<a href="stabilit" class="list-group-item">Liner Panel (Recubrimientos de pared)</a>
</div>
</div>
<div class="col-xs-12 col-sm-9">
<p class="pull-right visible-xs">
<button type="button" class="btn btn-primary btn-xs"
data-toggle="offcanvas">Toggle nav</button>
</p>
<div class="jumbotron">
<h1>Nylon</h1>
<p>Desde el punto de vista mecánico, ofrece:</p>
<p><ul><li>Resistencia al impacto; absorbe cargas que pueden llegar
a fracturar los dientes de un engrane metálico, ya que
Nylamid en sus dos presentaciones (normal y autolubricado)
posee una gran resistencia.
®
<li>Autolubricación; algunos rodamientos Nylamid se han mantenido
por años sin necesidad de lubricantes, pues Nylamid
SL color negro elimina este requerimiento, ya que ofrece
mayor resistencia al desgaste por fricción, evitando, además,
problemas de lubricación en situaciones difíciles.</li></ul></p>
</div>
<div class="row">
<div class="col-xs-6 col-lg-4">
<h2>Nyamid M</h2>
<p>Nylon Natural. sin aditivos.
Combina una adecuada resistencia
mecánica, rigidez y dureza con una
buena resistencia al desgaste.
Aprobado para trabajar en contacto
con alimentos según la norma
NMX-E-202-1993-SCFI.</p>
<p>
<a class="btn btn-default" href="nylon-m.php" role="button">Agregar »</a>
</p>
</div>
<div class="col-xs-6 col-lg-4">
<h2>Nylamid XL</h2>
<p>Contiene aceite integrado homogéneamente al nylon
para mejorar sus propiedades de resistencia al
desgaste y al impacto reduciendo la absorción de
humedad.
.</p>
<p>
<a class="btn btn-default" href="#" role="button">Agregar »</a>
</p>
</div>
<div class="col-xs-6 col-lg-4">
<h2>Nylamid 910</h2>
<p>Nylon estabilizado al calor a temperaturas
hasta de 127° C, ofrece mayor
tenacidad, flexibilidad y resistencia a
la fatiga que el Nylamid M.Nylon estabilizado al calor a temperaturas
hasta de 127° C, ofrece mayor
tenacidad, flexibilidad y resistencia a
la fatiga que el Nylamid M.</p>
<p>
<a class="btn btn-default" href="#" role="button">Agregar »</a>
</p>
</div>
<div class="col-xs-6 col-lg-4">
<h2>Nylamid SL</h2>
<p>Contiene partículas de bisulfuro de
molibdeno (MoS2) homogéneamente
dispersas, que mejoran sus propiedades de
resistencia al desgaste, conservando su
resistencia al impacto, común del nylon.</p>
<p>
<a class="btn btn-default" href="#" role="button">Agregar »</a>
</p>
</div>
</div>
</div>
</div>
<?php include 'inc/footer.php';?>
</div>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
<style type="text/css">
td, th {
padding: 5px;
border: 1px solid #ccc;
}
th {
text-align: center;
text-transform: uppercase;
background-color: #009688;
color: #fff;
}
.collapsible-body {
padding: 10px;
}
span.badge {
position: inherit;
}
span.badge.new {
font-size: 1rem;
}
div.collapsible-header.active {
background: #00bfa5;
color: #fff;
}
</style>
</head>
<body>
<?php include 'inc/nav-admin.php'; ?>
<div class="container" style="width: 85%;">
<div class="row">
<div class="col s12">
<ul class="collapsible" data-collapsible="accordion">
<li>
<div class="collapsible-header active">Región: NORTE</div>
<div class="collapsible-body">
<table class="table bordered striped">
<tr>
<th>ID</th>
<th>Sucursal</th>
<th>Incidentes</th>
</tr>
<tr>
<td><a href="#">1</td>
<td><a href="#">CEL</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">2</td>
<td><a href="#">CORPORATIVO</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">3</td>
<td><a href="#">Barragán 2</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">4</td>
<td><a href="#">Calzada del Valle</td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td><a href="#">5</td>
<td><a href="#">Centrika</td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td><a href="#">6</td>
<td><a href="#">Citadina</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">7</td>
<td><a href="#">EL REGIO</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">8</td>
<td><a href="#">Francisco de Quevedo</td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td><a href="#">9</td>
<td><a href="#">GALERÍAS MONTERREY</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">10</td>
<td><a href="#">Garza Sada</td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td><a href="#">11</td>
<td><a href="#">Guadalupe Centro</td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td><a href="#">12</td>
<td><a href="#">HACIENDA DEL SOL</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">13</td>
<td><a href="#">JARDINES DE LAS LOMAS</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">14</td>
<td><a href="#">MI PLAZA LOS ÁNGELES</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">15</td>
<td><a href="#">MISIÓN ANÁHUAC</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">16</td>
<td><a href="#">OMA MTY – TC</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">17</td>
<td><a href="#">PASEO LAS AMÉRICAS</td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td><a href="#">18</td>
<td><a href="#">PLAZA BOLIVAR</td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td><a href="#">19</td>
<td><a href="#">PLAZA QU</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">20</td>
<td><a href="#">PLAZA REMAX</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
</table>
</div>
</li>
<li>
<div class="collapsible-header">Región: NORESTE</div>
<div class="collapsible-body">
<table class="table bordered striped">
<tr>
<td><a href="#">21</td>
<td><a href="#">PROVEE MUGUERZA</td>
<td><a href="#">NORESTE</td>
<td><a href="#">SUC</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">22</td>
<td><a href="#">PROVEE OCA</td>
<td><a href="#">NORESTE</td>
<td><a href="#">SUC</td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">23</td>
<td><a href="#">Paseo La Fe</td>
<td><a href="#">NORESTE</td>
<td><a href="#">SUC</td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">24</td>
<td><a href="#">Plaza G3</td>
<td><a href="#">NORESTE</td>
<td><a href="#">SUC</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td><a href="#">25</td>
<td><a href="#">QUINTA MONTECARLO</td>
<td><a href="#">NORESTE</td>
<td><a href="#">SUC</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
</tr>
<tr>
<td><a href="#">26</td>
<td><a href="#">Real del Valle</td>
<td><a href="#">NORESTE</td>
<td><a href="#">SUC</td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">27</td>
<td><a href="#">SUC. 20 DE NOVIEMBRE ( N.L. )</td>
<td><a href="#">NORESTE</td>
<td><a href="#">SUC</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">28</td>
<td><a href="#">SUC. ABEDUL</td>
<td><a href="#">NORESTE</td>
<td><a href="#">SUC</td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">29</td>
<td><a href="#">SUC. ALFONSO REYES</td>
<td><a href="#">NORESTE</td>
<td><a href="#">SUC</td>
<td><a href="#"><Span class="badge" data-badge-caption="incidentes">0</span></td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">30</td>
<td><a href="#">SUC. AMAZONAS</td>
<td><a href="#">NORESTE</td>
<td><a href="#">SUC</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">31</td>
<td><a href="#">SUC. AMÉRICAS (Cd. Guadalupe)</td>
<td><a href="#">NORESTE</td>
<td><a href="#">SUC</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">32</td>
<td><a href="#">SUC. ANILLO VIAL</td>
<td><a href="#">NORESTE</td>
<td><a href="#">SUC</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
<tr>
<td><a href="#">33</td>
<td><a href="#">SUC. ANÁHUAC</td>
<td><a href="#">NORESTE</td>
<td><a href="#">SUC</td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
<td><a href="#"><Span class="new badge" data-badge-caption="incidentes nuevos">4</span></td>
</tr>
</table>
</div>
</li>
<li>
<div class="collapsible-header">Región: CENTRO</div>
<div class="collapsible-body">
</div>
</li>
<li>
<div class="collapsible-header">Región: SUR</div>
<div class="collapsible-body">
</div>
</li>
</ul>
<div class="center">
<a href="admin.php" class="btn waves-effect">Regresar</a>
</div>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".tab a").click(function() {
window.location.href = $(this).attr("href");
});
$(".button-collapse").sideNav();
$('.collapsible').collapsible();
});
</script>
</body>
</html><file_sep># midsa-onlinestore-demo
Demo of the Online Store for Midsa
<file_sep><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MoBOX</title>
<?php include("inc/meta-head.php"); ?>
<?php include("inc/scripts.php"); ?>
<?php include("inc/styles.php"); ?>
</head>
<body>
<?php include("inc/navbar.php"); ?>
<div class="container">
<div class="row">
<div class="col-xs-10">
<table>
<tr>
<td>Avance del Cierre del Mes de </td>
<td nowrap="nowrap">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Enero <span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#" onclick="loadCharts();">Enero</a></li>
<li><a href="#" onclick="loadCharts();">Febrero</a></li>
<li><a href="#" onclick="loadCharts();">Marzo</a></li>
</ul>
</div>
</td>
<td>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
2016 <span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#" onclick="loadCharts();">2016</a></li>
<li><a href="#" onclick="loadCharts();">2015</a></li>
<li><a href="#" onclick="loadCharts();">2014</a></li>
</ul>
</div>
</td>
</tr>
</table>
</div>
</div>
<br/>
<div class="row">
<div class="col-sm-6 col-md-4">
<div style="background: #7ebf34; color: #fff; padding: 5px; border-top-left-radius: 6px; border-top-right-radius: 6px;" align="center">
<h4>Cumplimiento</h4>
</div>
<div style="background: #8bd339; color: #fff; padding: 10px; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px;" align="center">
<a href="#" style="font-weight: bold; font-size: 28px; color: #fff; cursor: pointer;"></a>
<canvas id="modular-doughnut1" style="height: 250px;" height="250px"></canvas>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div style="background: #7ebf34; color: #fff; padding: 5px; border-top-left-radius: 6px; border-top-right-radius: 6px;" align="center">
<h4>Fin día</h4>
</div>
<div style="background: #8bd339; color: #fff; padding: 10px; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px;" align="center">
<span style="font-weight: bold; font-size: 28px; color: #fff;"></span>
<canvas id="modular-doughnut2" style="height: 250px;" height="250px"></canvas>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div style="background: #7ebf34; color: #fff; padding: 5px; border-top-left-radius: 6px; border-top-right-radius: 6px;" align="center">
<h4>Ejecución de JOBs</h4>
</div>
<div style="background: #8bd339; color: #fff; padding: 10px; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px;" align="center">
<span style="font-weight: bold; font-size: 28px; color: #fff;"></span>
<canvas id="modular-doughnut3" style="height: 250px;" height="250px"></canvas>
</div>
</div>
</div>
<p> </p>
<div class="row">
<div class="col-sm-6 col-md-6">
<div style="background: #7ebf34; color: #fff; padding: 5px; border-top-left-radius: 6px; border-top-right-radius: 6px;" align="center">
<h4>Fin Dia - RETEK</h4>
</div>
<div style="background: #8bd339; color: #fff; padding: 10px; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px;" align="center">
<a href="#" style="font-weight: bold; font-size: 28px; color: #fff; cursor: pointer;"></a>
<canvas id="modular-doughnut4"></canvas>
</div>
</div>
<div class="col-sm-6 col-md-6">
<div style="background: #7ebf34; color: #fff; padding: 5px; border-top-left-radius: 6px; border-top-right-radius: 6px;" align="center">
<h4>Incidentes por Servicio</h4>
</div>
<div style="background: #8bd339; color: #fff; padding: 10px; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px;" align="center">
<span style="font-weight: bold; font-size: 28px; color: #fff;"></span>
<canvas id="modular-doughnut5"></canvas>
</div>
</div>
</div>
<p> </p>
</div>
<script type="text/javascript">
loadCharts = function() {
var data = [],
barsCount = 50,
labels = new Array(barsCount),
updateDelayMax = 500,
$id = function(id){
return document.getElementById(id);
},
random = function(max){ return Math.round(Math.random()*100)},
random2 = function(min, max){ return Math.floor(Math.random() * (max - min + 1)) + min; }
helpers = Chart.helpers;
Chart.defaults.global.responsive = true;
var data1 = {
labels: [random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random()],
datasets: [
{
fillColor: "rgba(255,255,255,.4)",
strokeColor: "#369",
pointColor: "#336699",
pointHighlightFill: "#fff",
data: [random2(60, 100), random2(60, 100), random2(60, 100), random2(60, 100), random2(60, 100), random2(60, 100), random2(60, 100), random2(60, 100), random2(60, 100), random2(60, 100), random2(60, 100), random2(60, 100)]
},
{
fillColor: "rgba(255,255,255,.4)",
strokeColor: "#03f",
pointColor: "#336699",
pointHighlightFill: "#fff",
data: [random2(30, 60), random2(30, 60), random2(30, 60), random2(30, 60), random2(30, 60), random2(30, 60), random2(30, 60), random2(30, 60), random2(30, 60), random2(30, 60), random2(30, 60), random2(30, 60)]
},
{
fillColor: "rgba(255,255,255,.4)",
strokeColor: "#f90",
pointColor: "#336699",
pointHighlightFill: "#fff",
data: [random2(1, 30), random2(1, 30), random2(1, 30), random2(1, 30), random2(1, 30), random2(1, 30), random2(1, 30), random2(1, 30), random2(1, 30), random2(1, 30), random2(1, 30), random2(1, 30)]
}]
};
var data2 = {
labels: [random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random()],
datasets: [
{
fillColor: "rgba(255,255,255,.4)",
strokeColor: "#369",
pointColor: "#336699",
pointHighlightFill: "#fff",
data: [random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random2(60, 100)]
},
{
fillColor: "rgba(255,255,255,.4)",
strokeColor: "#369",
pointColor: "#336699",
pointHighlightFill: "#fff",
data: [random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random2(1, 30)]
}]
};
var data3 = {
labels: ["10MON", "10ABC", "10CTL", "10PHC", "10JIT", "10RST", "10AJL", "10UKL", "10IKL", "10SIS", "10MTY", "10KSR", "10AFR"],
datasets: [
{
fillColor: "#da3232",
pointHighlightFill: "#fff",
data: [random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random()]
},
{
fillColor: "#4990d0",
pointHighlightFill: "#fff",
data: [random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random(), random()]
}]
};
var options1 = {
animation: false,
showScale: true,
barShowStroke: false,
tooltipXPadding: 10,
tooltipYPadding: 6,
//tooltipFontSize: 18,
//tooltipFontStyle: 'bold',
// Boolean - If we want to override with a hard coded scale
scaleOverride: true,
// ** Required if scaleOverride is true **
// Number - The number of steps in a hard coded scale
scaleSteps: 2,
// Number - The value jump in the hard coded scale
scaleStepWidth: 50,
// Number - The scale starting value
scaleStartValue: 0,
bezierCurve : false,
pointStrokeColor: "#fff",
bezierCurve : false,
pointHighlightStroke: "#369",
scaleShowHorizontalLines: false
};
var options2 = {
animation: false,
showScale: true,
barShowStroke: false,
tooltipXPadding: 10,
tooltipYPadding: 6,
scaleOverride: true,
scaleSteps: 2,
scaleStepWidth: 50,
scaleStartValue: 0,
bezierCurve : false,
pointStrokeColor: "#fff",
bezierCurve : false,
pointHighlightStroke: "#369",
};
var options3 = {
animation: false,
showScale: true,
barShowStroke: false,
tooltipXPadding: 10,
tooltipYPadding: 6,
scaleOverride: true,
scaleSteps: 2,
scaleStepWidth: 50,
scaleStartValue: 0,
bezierCurve : false,
pointStrokeColor: "#fff",
bezierCurve : false,
pointHighlightStroke: "#369",
};
/*
var canvas = $id('interactive-bar');
var microBar = new Chart(canvas.getContext('2d')).Bar(data1, options);
helpers.addEvent(canvas, 'mousemove', function(evt){
var bars = microBar.getBarsAtEvent(evt);
if (bars.length > 0){
canvas.style.cursor = "pointer";
}
else {
canvas.style.cursor = "default";
}
});
helpers.addEvent(canvas, 'click', function(evt){
microBar.options.animation = true;
microBar.options.onAnimationComplete = function(){
this.showTooltip(this.activeElements, true);
};
var bars = microBar.getBarsAtEvent(evt);
helpers.each(bars, function(bar){
bar.value = Math.max(random(), 5);
});
if (bars.length > 0){
microBar.update();
}
});
*/
var canvas = $id('modular-doughnut1');
var linechart = new Chart(canvas.getContext('2d')).Line(data1, options1);
var canvas = $id('modular-doughnut2');
var linechart = new Chart(canvas.getContext('2d')).Line(data2, options2);
var canvas = $id('modular-doughnut3');
var linechart = new Chart(canvas.getContext('2d')).Bar(data3, options2);
myArray1 = [];
myArray2 = [];
myArray3 = [];
s1 = 1;
s2 = 2;
s3 = 3;
for (i=0; i<=12; i++) {
s1 += random2(1,3);
s2 += random2(1,3);
base = random2(5,20);
myArray1[i] = base;
myArray2[i] = base + s1;
myArray3[i] = base + s1 + s2 + s2;
}
//myArray = [random2(5, 20), random2(5, 20), random2(5, 20), random2(5, 20), random2(5, 20), random2(5, 20), random2(5, 20), random2(5, 20), random2(5, 20), random2(5, 20)];
var data5 = {
labels: [random(), random(), random(), random(), random(), random(), random(), random(), random(), random()],
datasets: [
{
fillColor: "#de739c",
pointColor: "#336699",
pointHighlightFill: "#fff",
data: myArray3
},
{
fillColor: "#3163d6",
pointColor: "#336699",
pointHighlightFill: "#fff",
data: myArray2
},
{
fillColor: "#fff773",
pointColor: "#336699",
pointHighlightFill: "#fff",
data: myArray1
}]
};
var options5 = {
animation: false,
showScale: true,
barShowStroke: false,
tooltipXPadding: 10,
tooltipYPadding: 6,
scaleOverride: false,
scaleSteps: 2,
scaleStepWidth: 50,
scaleStartValue: 0,
pointStrokeColor: "#fff",
bezierCurve : false,
pointDot : false,
datasetStroke : false
};
var canvas = $id('modular-doughnut5');
var linechart = new Chart(canvas.getContext('2d')).Line(data5, options5);
array4 = []
for (i=0; i<=40; i++) {
array4[i] = random2(20,60);
}
var data4 = {
labels: array4,
datasets: [
{
fillColor: "rgba(255,255,255,.0)",
strokeColor: "#666",
pointColor: "#336699",
pointHighlightFill: "#fff",
data: array4
}]
};
var options4 = {
animation: false,
showScale: true,
barShowStroke: false,
tooltipXPadding: 10,
tooltipYPadding: 6,
scaleOverride: true,
scaleSteps: 2,
scaleStepWidth: 50,
scaleStartValue: 0,
bezierCurve : false,
pointStrokeColor: "#fff",
bezierCurve : false,
pointHighlightStroke: "#369",
pointDot : false
};
var canvas = $id('modular-doughnut4');
var linechart = new Chart(canvas.getContext('2d')).Line(data4, options4);
$('#modular-doughnut4').css('background-color', 'rgba(255, 255, 255, 1)');
$('#modular-doughnut5').css('background-color', 'rgba(255, 255, 255, .5)');
};
(function(){
loadCharts();
})();
</script>
<script src="js/bootstrap.js"></script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
</head>
<body class="grey lighten-4">
<br>
<div class="container">
<div class="card">
<div class="card-content">
<span class="card-title" style="font-weight: 400;">INICIAR SESIÓN</span>
<div class="input-field col s12">
<select>
<option value="" disabled selected>Elija su sucursal</option>
<option value="1">APODACA</option>
<option value="2">ESCOBEDO</option>
<option value="3">LA FE</option>
</select>
<label>Elija su sucursal</label>
</div>
<br>
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input id="icon_prefix" type="text" class="validate">
<label for="icon_prefix">Nombre de usuario</label>
</div>
<br>
<div class="input-field col s12">
<i class="material-icons prefix">lock</i>
<input id="icon_telephone" type="password" class="validate">
<label for="icon_telephone">Contraseña</label>
</div>
<br>
<div class="input-field col s12 center">
<a href="sucursal2.php" class="btn btn-large waves-effect">Ingresar</a>
</div>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".button-collapse").sideNav();
$('select').material_select();
});
</script>
</body>
</html><file_sep><!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Midsa - Carrito</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/carousel.css" rel="stylesheet">
</head>
<body>
<div class="container">
<?php include 'inc/header.php'; ?>
<br /> <br /> <br /> <br /> <br />
<br />
<table width="100%">
<tr>
<td width="50%">Carrito de compras para: <span style="font-size: 20px;">Fernando</span></td>
<td width="50%" align="right">Tiempo estimdo de entrega: <span style="font-size: 20px;">3 días</span></td>
</tr>
</table>
<br />
<table class="table table-striped" id="items">
<tr id="item0">
<th>#</th>
<th width="50%">Artículo</th>
<th>Cantidad</th>
<th>Presentación</th>
<th>Dimensiones</th>
<th>Precio</th>
<th></th>
</tr>
<tr id="item1">
<td>1</td>
<td><a href="nylon-m.php">Nylamid M</a></td>
<td>1</td>
<td>Placa</td>
<td>13 x 25</td>
<td nowrap="nowrap" align="right">$ 35.50</td>
<td><button type="button" class="btn btn-danger" onclick="removeItem('item1');">Remover</button></td>
</tr>
<tr id="item2">
<td>2</td>
<td><a href="nylon-m.php">Nylamid 910</a></td>
<td>1</td>
<td>Placa</td>
<td>13 x 25</td>
<td nowrap="nowrap" align="right">$ 92.99</td>
<td><button type="button" class="btn btn-danger" onclick="removeItem('item2');">Remover</button></td>
</tr>
<tr id="item3">
<td>3</td>
<td><a href="nylon-m.php">LEXAN® 934</a></td>
<td>1</td>
<td>Cilindro</td>
<td>-</td>
<td nowrap="nowrap" align="right">$ 1,650</td>
<td><button type="button" class="btn btn-danger" onclick="removeItem('item3');">Remover</button></td>
</tr>
<tr style="background: #fff; border:0;">
<td colspan="5" align="right">
<p>Sub-total:</p>
<p>IVA:</p>
<p><b>Total</b></p>
</td>
<td nowrap="nowrap" align="right">
<p>$ 1,778.49</p>
<p>$ 284.55</p>
<p><b style="font-size: 18px;">$ 2,063.05</b></p>
</td>
<td></td>
</tr>
</table>
<br />
<div align="right">
<button type="button" class="btn btn-lg btn-primary" onclick="window.location.href='login.php'">Proceder a pagar</button>
</div>
<br /> <br />
<?php include 'inc/footer.php';?>
</div>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type="text/javascript">
function addToCart() {
var badge = '<span class="badge">3</span>';
var node = document.createElement("span");
node.className = "badge";
var textnode = document.createTextNode("3");
node.appendChild(textnode);
document.getElementById("carrito").appendChild(node);
}
addToCart();
function removeItem(rowid) {
var row = document.getElementById(rowid);
row.parentNode.removeChild(row);
}
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
</head>
<body class="grey lighten-4">
<?php include 'inc/nav-sucursal.php'; ?>
<div class="container">
<div class="card">
<div class="card-content">
<span class="card-title" style="font-weight: 400;">
Hola <strong>Claudia</strong><br>
Sucursal: <strong>APODACA</strong>
</span>
</div>
<div class="card-action">
<h5>Tus bultos a recibir hoy <strong>17/08/2016</strong> son:</h5>
<ul>
<li>
<p>
<input type="checkbox" id="test5" />
<label for="test5" class="black-text">Bulto 25 <a href="scan2.php" class="btn waves-effect tooltipped" data-position="top" data-delay="50" data-tooltip="En Tienda/Sucursal se ESCANEA el bulto y se cierra el ciclo CHECK-OUT">Escanear bulto</a></label>
</p>
<br>
</li>
<li>
<p>
<input type="checkbox" id="test6" checked="checked" disabled="disabled" />
<label for="test6" class="black-text">Bulto 22 <span class="grey-text">(recibido)</span></label>
</p>
<br>
</li>
<li>
<p>
<input type="checkbox" id="test6" checked="checked" disabled="disabled" />
<label for="test6" class="black-text">Bulto 23 <span class="grey-text">(recibido)</span></label>
</p>
<br>
</li>
<li>
<p>
<input type="checkbox" id="test6" checked="checked" disabled="disabled" />
<label for="test6" class="black-text">Bulto 24 <span class="grey-text">(recibido)</span></label>
</p>
<br>
</li>
</ul>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".button-collapse").sideNav();
});
</script>
</body>
</html><file_sep>$(function() {
var App = {
init: function() {
App.attachListeners();
},
config: {
reader: "code_128",
length: 10
},
attachListeners: function() {
var self = this;
$(".controls input[type=file]").on("change", function(e) {
$("#founded").css("display", "none");
$("#result_strip").html("");
if (e.target.files && e.target.files.length) {
App.decode(URL.createObjectURL(e.target.files[0]));
}
});
},
_accessByPath: function(obj, path, val) {
var parts = path.split('.'),
depth = parts.length,
setter = (typeof val !== "undefined") ? true : false;
return parts.reduce(function(o, key, i) {
if (setter && (i + 1) === depth) {
o[key] = val;
}
return key in o ? o[key] : {};
}, obj);
},
_convertNameToState: function(name) {
return name.replace("_", ".").split("-").reduce(function(result, value) {
return result + value.charAt(0).toUpperCase() + value.substring(1);
});
},
detachListeners: function() {
$(".controls input[type=file]").off("change");
},
decode: function(src) {
var self = this,
config = $.extend({}, self.state, {src: src});
Quagga.decodeSingle(config, function(result) {});
},
setState: function(path, value) {
var self = this;
if (typeof self._accessByPath(self.inputMapper, path) === "function") {
value = self._accessByPath(self.inputMapper, path)(value);
}
self._accessByPath(self.state, path, value);
//console.log(JSON.stringify(self.state));
App.detachListeners();
App.init();
},
inputMapper: {
inputStream: {
size: function(value){
return parseInt(value);
}
},
numOfWorkers: function(value) {
return parseInt(value);
},
decoder: {
readers: function(value) {
if (value === 'ean_extended') {
return [{
format: "ean_reader",
config: {
supplements: [
'ean_5_reader', 'ean_2_reader'
]
}
}];
}
return [{
format: value + "_reader",
config: {}
}];
}
}
},
state: {
inputStream: {
size: 800
},
locator: {
patchSize: "medium",
halfSample: false
},
numOfWorkers: 1,
decoder: {
readers: [{
format: "code_128_reader",
config: {}
},
{
format: "code_39_reader",
config: {}
},
{
format: "code_39_vin_reader",
config: {}
},
{
format: "ean_reader",
config: {}
},
{
format: "upc_reader",
config: {}
},
{
format: "upc_e_reader",
config: {}
},
{
format: "codabar_reader",
config: {}
},
{
format: "i2of5_reader",
config: {}
}]
},
locate: true,
src: null
}
};
App.init();
Quagga.onProcessed(function(result) {
var drawingCtx = Quagga.canvas.ctx.overlay,
drawingCanvas = Quagga.canvas.dom.overlay;
if (result) {
if (result.boxes) {
drawingCtx.clearRect(0, 0, parseInt(drawingCanvas.getAttribute("width")), parseInt(drawingCanvas.getAttribute("height")));
result.boxes.filter(function (box) {
return box !== result.box;
}).forEach(function (box) {
Quagga.ImageDebug.drawPath(box, {x: 0, y: 1}, drawingCtx, {color: "green", lineWidth: 4});
});
}
if (result.box) {
Quagga.ImageDebug.drawPath(result.box, {x: 0, y: 1}, drawingCtx, {color: "#00F", lineWidth: 4});
}
if (result.codeResult && result.codeResult.code) {
Quagga.ImageDebug.drawPath(result.line, {x: 'x', y: 'y'}, drawingCtx, {color: 'red', lineWidth: 6});
} else {
$("#result_strip").prepend("<h5>El código no puede ser interpretado, intente de nuevo.</h5>");
}
} else {
$("#result_strip").prepend("<h5>No se encontró código, intente de nuevo.</h5>");
}
});
Quagga.onDetected(function(result) {
var code = result.codeResult.code,
$node,
canvas = Quagga.canvas.dom.image;
$("#founded").css("display", "block");
$("#result_strip").prepend("<p><b>Código escaneado: </b></p><h5>" + code + "</h5>");
});
});<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
</head>
<body>
<?php include 'inc/nav-admin.php'; ?>
<div class="container" style="width: 85%;">
<div class="section">
<div class="row">
<div class="col s12 m6">
<p><a href="dashboard.php" class="btn-large" style="width: 90%">Monitor <i class="material-icons right">dashboard</i></a></p>
<br>
<p><a href="tracking.php" class="btn-large" style="width: 90%">Tracking de bultos <i class="material-icons right">list</i></a></p>
<br>
<p><a href="#" class="btn-large" style="width: 90%">Reportes <i class="material-icons right">list</i></a></p>
<br>
</div>
<div class="col s12 m6">
<div class="card">
<ul class="collection with-header">
<li class="collection-header"><h4>Administración general</h4></li>
<a href="usuarios.php" class="collection-item"><i class="material-icons">person</i> Usuarios</a>
<a href="sucursales.php" class="collection-item"><i class="material-icons">store</i> Sucursales y Tiendas</a>
<a href="#!" class="collection-item"><i class="material-icons">directions_bus</i> Transportistas</a>
<a href="#!" class="collection-item"><i class="material-icons">open_with</i> Rutas</a>
</ul>
</div>
</div>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".tab a").click(function() {
window.location.href = $(this).attr("href");
});
$(".button-collapse").sideNav();
$('.collapsible').collapsible();
});
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
</head>
<body class="grey lighten-4">
<div class="navbar-fixed">
<?php include 'inc/nav-transportista.php'; ?>
</div>
<div class="container">
<div class="card-panel">
<div>
<h5>Captura de Indicencias</h5>
<form class="col s12">
<div class="row input-field col s12">
<select class="light-green lighten-5">
<option value="" disabled="disabled" selected="selected">¿Dónde ocurre el incidente?</option>
<option value="1">Etiqueta</option>
<option value="2">Paquete</option>
<option value="3">Ruta/Sucursal</option>
</select>
</div>
<div class="row input-field col s12 center">
<div class="controls">
<fieldset class="input-group">
<input type="file" accept="image/*;capture=camera">
<button>Rerun</button>
</fieldset>
<fieldset class="reader-config-group">
<label>
<span>Barcode-Type</span>
<select name="decoder_readers">
<option value="code_128" selected="selected">Code 128</option>
<option value="code_39">Code 39</option>
<option value="code_39_vin">Code 39 VIN</option>
<option value="ean">EAN</option>
<option value="ean_extended">EAN-extended</option>
<option value="ean_8">EAN-8</option>
<option value="upc">UPC</option>
<option value="upc_e">UPC-E</option>
<option value="codabar">Codabar</option>
<option value="i2of5">ITF</option>
</select>
</label>
<label>
<span>Resolution (long side)</span>
<select name="input-stream_size">
<option value="320">320px</option>
<option value="640">640px</option>
<option selected="selected" value="800">800px</option>
<option value="1280">1280px</option>
<option value="1600">1600px</option>
<option value="1920">1920px</option>
</select>
</label>
<label>
<span>Patch-Size</span>
<select name="locator_patch-size">
<option value="x-small">x-small</option>
<option value="small">small</option>
<option selected="selected" value="medium">medium</option>
<option value="large">large</option>
<option value="x-large">x-large</option>
</select>
</label>
<label>
<span>Half-Sample</span>
<input type="checkbox" name="locator_half-sample">
</label>
<label>
<span>Workers</span>
<select name="numOfWorkers">
<option value="0">0</option>
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="8">8</option>
</select>
</label>
</fieldset>
</div>
<div id="result_strip">
<ul class="thumbnails"></ul>
</div>
<div id="interactive" class="viewport"><canvas class="imgBuffer" width="800" height="600"></canvas><canvas class="drawingBuffer" width="800" height="600"></canvas><br clear="all"></div>
</div>
<div class="row input-field col s12 center">
<input type="file" id="file2" style="display: none;"/>
<button type="button" id="file1" class="btn waves-effect waves-light">Adjuntar evidencia <i class="material-icons right">attach_file</i></button>
</div>
<div class="row input-field col s12">
<i class="material-icons prefix">mode_edit</i>
<textarea id="textarea1" class="materialize-textarea light-green lighten-5"></textarea>
<label for="textarea1">Comentarios</label>
</div>
<div class="row right">
<button type="sutbmit" class="btn waves-effect waves-light">Enviar <i class="material-icons right">send</i></button>
</div>
<p> </p>
<p> </p>
</form>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script src="js/quagga.js"></script>
<script src="js/file_input.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".button-collapse").sideNav();
$('select').material_select();
});
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MoBOX Login</title>
<?php include("inc/meta-head.php"); ?>
<?php include("inc/scripts.php"); ?>
<?php include("inc/styles.php"); ?>
<link href="css/signin.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<span class="navbar-brand">MoBOX</span>
</div>
</nav>
<div class="container">
<form class="form-signin" action="home.php">
<h3 class="form-signin-heading">Inicio de sesión</h3>
<p>
<label for="inputEmail" class="sr-only">Dirección email</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Usuario" autofocus>
</p>
<p>
<label for="inputPassword" class="sr-only">Contraseña</label>
<input type="password" id="inputPassword" class="form-control" placeholder="<PASSWORD>">
</p>
<button class="btn btn-lg btn-primary btn-block" type="submit">Ingresar</button>
</form>
</div>
<script src="js/bootstrap.js"></script>
</body>
</html><file_sep>
if (!window.customerLoginController) {
window.customerLoginController =
{
registry: [],
loginButtonLookup: {},
loginButtonIds: [],
registerCustomerLoginWidget: function (emailId, passwordId, buttonId, errorTextId, action) {
this.registry.push(new CustomerLoginAjaxManager(emailId, passwordId, errorTextId, action));
this.bindLoginButton(buttonId);
if (buttonId != null && buttonId.length > 0)
this.loginButtonLookup[buttonId] = this.registry[this.registry.length - 1];
},
bindLoginButton: function (buttonId) {
if (buttonId != null && buttonId.length > 0) {
if ($.inArray(buttonId, this.loginButtonIds) != -1)
return;
this.loginButtonIds.push(buttonId);
$("#" + buttonId).click(function (event) {
event.preventDefault();
var controller = window.customerLoginController.loginButtonLookup[buttonId];
controller.login();
return false;
});
}
}
}
}
var CustomerLoginAjaxManager = function (emailId, passwordId, errorTextId, action) {
this._emailId = emailId;
this._passwordId = <PASSWORD>;
this._errorTextId = errorTextId;
this._action = action;
var self = this;
$(function () {
self.init();
});
};
CustomerLoginAjaxManager.prototype = {
init: function () {
},
login: function () {
$form = $("<form action='" + this._action + "' method='post'></form>");
$form.append("<input type='hidden' value='" + $("#" + this._emailId).val() + "' id='txtMergeUsername' name='txtMergeUsername' />");
$form.append("<input type='hidden' value='" + $("#" + this._passwordId).val() + "' id='txtMergePassword' name='txtMergePassword' />");
$form.append("<input type='hidden' value='ac integrity check' id='acIntegrityCheck' name='acIntegrityCheck' />");
$form.appendTo('body').submit();
}
};<file_sep>SubMenuItemHoverFunction = function()
{
var subMenuItemElements = document.getElementsByTagName("div");
for(i = 0; i < subMenuItemElements.length; i++)
{
if(subMenuItemElements[i].className.indexOf("SubMenuItem") > -1)
{
subMenuItemElements[i].onmouseover = function() { this.className += " SubMenuItemHover"; }
subMenuItemElements[i].onmouseout = function() { this.className = this.className.replace(new RegExp(" SubMenuItemHover\\b"), ""); }
}
else if(subMenuItemElements[i].className.indexOf("HorizontalNavItem") > -1)
{
subMenuItemElements[i].onmouseover = function() { this.className += " HorizontalNavItemHover"; }
subMenuItemElements[i].onmouseout = function() { this.className = this.className.replace(new RegExp(" HorizontalNavItemHover\\b"), ""); }
}
else if(subMenuItemElements[i].className.indexOf("ControlLink") > -1)
{
subMenuItemElements[i].onmouseover = function() { this.className += " ControlLinkHover"; }
subMenuItemElements[i].onmouseout = function() { this.className = this.className.replace(new RegExp(" ControlLinkHover\\b"), ""); }
}
}
}<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
</head>
<body class="grey lighten-4">
<div class="navbar-fixed">
<?php include 'inc/nav-cd.php'; ?>
</div>
<div class="container">
<div class="card">
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">Rampa A1<i class="material-icons right">more_vert</i></span>
<div class="divider"></div>
<p><b>15</b> bultos asignados</p>
<h5><b>3</b> bultos sin asignar</h5>
<p>8 en TRÁNSITO</p>
<p>4 ENTREGADOS</p>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4"> <i class="material-icons right">close</i></span>
<ul>
<li>- Bulto 34 <a href="#" class="btn waves-effect tooltipped" style="width: 100%;" data-position="top" data-delay="50" data-tooltip="Aquí es donde se inicia CHECK-IN el seguimiento del bulto">Asignar ruta/transportista</a><br><br></li>
<li>- Bulto 35 <a href="#" class="btn waves-effect tooltipped" style="width: 100%;" data-position="top" data-delay="50" data-tooltip="Aquí es donde se inicia CHECK-IN el seguimiento del bulto">Asignar ruta/transportista</a><br><br></li>
<li>- Bulto 38 <a href="#" class="btn waves-effect tooltipped" style="width: 100%;" data-position="top" data-delay="50" data-tooltip="Aquí es donde se inicia CHECK-IN el seguimiento del bulto">Asignar ruta/transportista</a><br><br></li>
</ul>
</div>
</div>
<div class="card">
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">Rampa A2<i class="material-icons right">more_vert</i></span>
<div class="divider"></div>
<p><b>8</b> bultos asignados</p>
<h5><b>1</b> bultos sin asignar</h5>
<p>0 en TRÁNSITO</p>
<p>7 ENTREGADOS</p>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4"> <i class="material-icons right">close</i></span>
<ul>
<li>- Bulto 12 <a href="#" class="btn waves-effect tooltipped" style="width: 100%;" data-position="top" data-delay="50" data-tooltip="Aquí es donde se inicia CHECK-IN el seguimiento del bulto">Asignar ruta/transportista</a><br><br></li>
</ul>
</div>
</div>
<div class="card">
<div class="card-content">
<span class="card-title grey-text text-darken-4">Rampa B1</span>
<div class="divider"></div>
<p><b>0</b> bultos asignados</p>
<p>0 en TRÁNSITO</p>
<p>0 ENTREGADOS</p>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4"> <i class="material-icons right">close</i></span>
</div>
</div>
<div class="card">
<div class="card-content">
<span class="card-title activator grey-text text-darken-4">Rampa B2<i class="material-icons right">more_vert</i></span>
<div class="divider"></div>
<p><b>9</b> bultos asignados</p>
<h5><b>2</b> bultos sin asignar</h5>
<p>5 en TRÁNSITO</p>
<p>2 ENTREGADOS</p>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4"> <i class="material-icons right">close</i></span>
<ul>
<li>- Bulto 84 <a href="#" class="btn waves-effect tooltipped" style="width: 100%;" data-position="top" data-delay="50" data-tooltip="Aquí es donde se inicia CHECK-IN el seguimiento del bulto">Asignar ruta/transportista</a><br><br></li>
<li>- Bulto 86 <a href="#" class="btn waves-effect tooltipped" style="width: 100%;" data-position="top" data-delay="50" data-tooltip="Aquí es donde se inicia CHECK-IN el seguimiento del bulto">Asignar ruta/transportista</a><br><br></li>
</ul>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".button-collapse").sideNav();
});
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
</head>
<body>
<?php include 'inc/nav-transportista.php'; ?>
<div class="container">
<br>
<h5>MIS RUTAS</h5>
<p>Detalle de la ruta</p>
Bultos: <b>12</b><br>
Sucursal: <b>Periférico</b>
<p><img src="img/ruta.jpg" style="border: 1px solid #ccc;" /></p>
<a href="misrutas.php" class="btn waves-effect">Regresar</a>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".button-collapse").sideNav();
});
</script>
</body>
</html><file_sep><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/png" href="favicon.ico">
<title>Fyolo | Publicidad</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css/rubick_pres.css" />
<!-- Fonts and icons -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" />
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:400,700|Material+Icons" />
<link rel="stylesheet" type="text/css" href="css/fonts/pe-icon-7-stroke.css" />
<link rel="stylesheet" type="text/css" href="css/fonts/Rubik-Fonts.css" />
<style>
h3 {
text-transform: none !important;
}
.section-header .separator {
margin: 0em auto 2em;
}
.section .parallax > img{
width: 100%;
min-height: 0;
min-width: 0;
}
.section-header h1{
text-shadow: -2px 2px 30px rgba(0, 0, 0, 0.25), -2px 4px 14px rgba(0, 0, 0, 0.1);
}
.section-header h5{
text-shadow: 0px 0px 11px rgba(0, 0, 0, 0.3);
}
.section-header .content{
top: 42%;
}
.section-we-are-1 .title{
max-width: 960px;
}
.card .icon ~ h3{
margin-bottom: 10px;
}
.section-with-hover .project .content{
text-align: center;
}
.section-with-hover .project .over-area{
background: rgba(0, 0, 0, .83);
}
.section-clients-2{
padding: 6em 0 1em;
}
.section-clients-2 .nav-text li {
margin: 0 15px 10px 15px;
}
.section-contact-3 .contact-container .address-container{
width: 28%;
background-color: #FFFFFF;
height: 470px;
top: 50px;
padding: 20px;
}
.section-contact-3 .address{
margin-top: 40px;
}
.section-we-made-3 .content{
padding: 0 15px;
text-align: center;
}
.section-we-made-3 .over-area .content h3{
margin: 5px 0 20px;
}
.section-we-made-3 .over-area .content p{
font-size: .9em;
color: #898989;
}
.section-we-made-3 .over-area .content h5{
margin-bottom: 0px;
margin-top: 20px;
}
.copyright a{
color: #FFFFFF;
}
.section-team-2 .team .member p {
font-size: .9em;
padding: 0 10px;
}
.card{
margin-bottom: 30px;
}
.section-with-hover .project .over-area.over-area-sm .content p {
font-size: .85em;
}
.section-with-hover .project .over-area.over-area-sm .content h4 {
font-size: 1.6em;
}
.logo{
display: block;
margin: 0 auto 10px;
width: 61px;
height: 61px;
border-radius: 50%;
border: 1px solid #333333;
overflow: hidden;
}
.logo img{
width: 100%;
height: 100%;
}
.loading .loading-container p {
font-size: 30px;
width: 220px;
margin: 0 auto;
margin-bottom: 30px;
height: 35px;
}
.loading .logo{
opacity: 0;
transition: all 0.9s;
-webkit-transition: all 0.9s;
-moz-transition: all 0.9s;
}
.loading .logo.visible{
opacity: 1;
}
.sharrre.btn{
color: #444444;
border-color: #444444;
font-weight: 400;
}
.address .col-md-6{
padding-right: 7px;
padding-left: 7px;
}
a.img-class{
opacity: 1;
}
a.img-class:hover{
opacity: .9;
}
@media (max-width: 1200px){
.section-contact-3 .contact-container .address-container{
height: 520px;
}
}
</style>
</head>
<body>
<nav class="navbar navbar-default navbar-transparent navbar-fixed-top navbar-burger" role="navigation">
<!-- if you want to keep the navbar hidden you can add this class to the navbar "navbar-burger"-->
<div class="container">
<div class="navbar-header">
<button id="menu-toggle" type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar bar1"></span>
<span class="icon-bar bar2"></span>
<span class="icon-bar bar3"></span>
</button>
<a target="_blank" href="?ref=presentation-page" class="navbar-brand" style="padding: 0;">
<img src="img/logo-fyolo.png">
</a>
</div>
<div class="collapse navbar-collapse" >
<ul class="nav navbar-nav navbar-right navbar-uppercase">
<li>
<a href="" data-scroll="true" data-id="#howitworks">
CÓMO FUNCIONA
</a>
</li>
<li>
<a href="" data-scroll="true" data-id="#buynow">
CONTRATA
</a>
</li>
<li>
<a href="" data-scroll="true" data-id="#whoWeAre">
ACERCA DE FYOLO
</a>
</li>
<li>
<a href="" data-scroll="true" data-id="#contact">
CONTÁCTANOS
</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="wrapper">
<div class="section section-header">
<div class="parallax pattern-image">
<img src="img/gas-station5.jpg"/>
<div class="container">
<div class="content">
<!--h1>Fyolo</h1-->
<h1><img src="img/logo-fyolo2.png" /></h1>
<div class="separator-container">
<div class="separator line-separator">∎</div>
</div>
<h5 style="text-shadow: 0px 0px 5px #000;">Por fin en México, la mejor plataforma de despacho y pago de combustible,<br/>
exclusiva para gasolineras desde cualquier Smartphone.</h5>
</div>
</div>
</div>
<a href="" data-scroll="true" data-id="#howitworks" class="scroll-arrow hidden-xs hidden-sm">
<i class="fa fa-angle-down"></i>
</a>
</div>
<div class="section section-we-do-2" id="howitworks" style="background-color: #fff; background-image: -webkit-linear-gradient(#fff,#F9F7FC); background-image: linear-gradient(#fff,#F9F7FC); background-repeat: no-repeat;">
<div class="container">
<div class="row">
<div class="title add-animation">
<h2>¿Cómo funciona?</h2>
<div class="separator-container">
<div class="separator line-separator">∎</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="card add-animation animation-1">
<div class="icon">
<img src="img/buddy1.png" />
</div>
<h3>Afilia a tu gasolinera</h3>
<p>Únete a la red fyolo hoy mismo. Te presentamos a nuevos clientes y a todos los que ya tienes.</p>
</div>
</div>
<div class="col-md-4">
<div class="card add-animation animation-2">
<div class="icon">
<img src="img/connect.png" />
</div>
<h3>Conectate a fyolo</h3>
<p>Crea clientes más leales y produce más ganancias con promociones especiales.</p>
</div>
</div>
<div class="col-md-4">
<div class="card add-animation animation-3">
<div class="icon">
<img src="img/buddy2.png" />
</div>
<h3>Disfruta de los beneficios</h3>
<p>Empieza a disfrutar de todos los beneficios que tiene para ti y tus clientes.</p>
</div>
</div>
</div>
</div>
</div>
<div class="section section-we-made-3" id="buynow">
<div class="container">
<div class="row">
<div class="title add-animation">
<h2>Contrata hoy mismo</h2>
<div class="separator-container">
<div class="separator line-separator">∎</div>
</div>
<h5>Y empieza a disfrutar de todos los beneficios que tiene para ti y tus clientes.</h5>
<p> </p>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<!-- Wizard container -->
<div class="wizard-container">
<div class="card wizard-card" data-color="red" id="wizard">
<form action="" method="">
<!-- You can switch " data-color="blue" " with one of the next bright colors: "green", "orange", "red", "purple" -->
<div class="wizard-header">
<h3 class="wizard-title">Contrata</h3>
<h5>This information will let us know more about you.</h5>
</div>
<div class="wizard-navigation">
<ul>
<li><a href="#details" data-toggle="tab">REGÍSTRATE O INGRESA</a></li>
<li><a href="#captain" data-toggle="tab">ELIGE UN PAQUETE</a></li>
<li><a href="#description" data-toggle="tab">ORDENA</a></li>
</ul>
</div>
<div class="tab-content">
<div class="tab-pane" id="details">
<div class="row">
<div class="col-sm-6">
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">email</i>
</span>
<div class="form-group label-floating">
<label class="control-label">Your Email</label>
<input name="name" type="text" class="form-control">
</div>
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">lock_outline</i>
</span>
<div class="form-group label-floating">
<label class="control-label">Your Password</label>
<input name="name2" type="<PASSWORD>" class="form-control">
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group label-floating">
<label class="control-label">Country</label>
<select class="form-control">
<option disabled="" selected=""></option>
<option value="Afghanistan"> Afghanistan </option>
<option value="Albania"> Albania </option>
<option value="Algeria"> Algeria </option>
<option value="American Samoa"> American Samoa </option>
<option value="Andorra"> Andorra </option>
<option value="Angola"> Angola </option>
<option value="Anguilla"> Anguilla </option>
<option value="Antarctica"> Antarctica </option>
<option value="...">...</option>
</select>
</div>
<div class="form-group label-floating">
<label class="control-label">Daily Budget</label>
<select class="form-control">
<option disabled="" selected=""></option>
<option value="Afghanistan"> < $100 </option>
<option value="Albania"> $100 - $499 </option>
<option value="Algeria"> $499 - $999 </option>
<option value="American Samoa"> $999+ </option>
</select>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="captain">
<h4 class="info-text">What type of room would you want? </h4>
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="col-sm-4">
<div class="choice" data-toggle="wizard-radio" rel="tooltip" title="This is good if you travel alone.">
<input type="radio" name="job" value="Design">
<div class="icon">
<i class="material-icons">weekend</i>
</div>
<h6>Single</h6>
</div>
</div>
<div class="col-sm-4">
<div class="choice" data-toggle="wizard-radio" rel="tooltip" title="Select this room if you're traveling with your family.">
<input type="radio" name="job" value="Code">
<div class="icon">
<i class="material-icons">home</i>
</div>
<h6>Family</h6>
</div>
</div>
<div class="col-sm-4">
<div class="choice" data-toggle="wizard-radio" rel="tooltip" title="Select this option if you are coming with your team.">
<input type="radio" name="job" value="Code">
<div class="icon">
<i class="material-icons">business</i>
</div>
<h6>Business</h6>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="description">
<div class="row">
<h4 class="info-text"> Drop us a small description.</h4>
<div class="col-sm-6 col-sm-offset-1">
<div class="form-group">
<label>Room description</label>
<textarea class="form-control" placeholder="" rows="6"></textarea>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label class="control-label">Example</label>
<p class="description">"The room really nice name is recognized as being a really awesome room. We use it every sunday when we go fishing and we catch a lot. It has some kind of magic shield around it."</p>
</div>
</div>
</div>
</div>
</div>
<div class="wizard-footer">
<div class="pull-right">
<input type='button' class='btn btn-next btn-fill btn-danger btn-wd' name="SIGUIENTE" value="SIGUIENTE"/>
<input type='button' class='btn btn-finish btn-fill btn-danger btn-wd' name="TERMINAR" value="TERMINAR" />
</div>
<div class="pull-left">
<input type='button' class='btn btn-previous btn-fill btn-default btn-wd' name="ANTERIOR" value="ANTERIOR" />
</div>
<div class="clearfix"></div>
</div>
</form>
</div>
</div> <!-- wizard container -->
</div>
</div> <!-- row -->
</div>
</div>
<div class="section section-we-are-1" id="whoWeAre" style="background-color: #fff; background-image: -webkit-linear-gradient(#F9F7FC, #fff); background-image: linear-gradient(#F9F7FC, #fff); background-repeat: no-repeat;">
<div class="container">
<div class="row">
<div class="title" id="animationTest">
<h2>Acerca de Fyolo</h2>
<div class="separator-container">
<div class="separator line-separator">∎</div>
</div>
<p class="large">
Con esta nueva aplicación, el despacho será más rápido; además, tendrás reportes de los hábitos de consumo de tus clientes y podrás ofrecerles incentivos para que vuelvan a tu estación.
<br/>
<br/>
Podras microsegmentar a tus clientes y desarrollar estrategias especializadas para ellos.
</p>
</div>
</div>
</div>
</div>
<div class="section section-contact-3" id="contact">
<div class="contact-container">
<div class="address-container add-animation animation-1">
<div class="address">
<h4>Nuestras oficinas</h4>
<p class="text-gray">
Av Paseo de los Leones 1684,<br/>
Leones, 64610<br/>
<NAME>.
Tel. <a href="#">+52 1 (81) 8850 0777</a>
</p>
<a target="_blank" href="contact-us" class="btn btn-green btn-contact">
CONTACTANOS <i class="fa fa-paper-plane"></i>
</a>
</div>
</div>
<div class="map">
<div id="contactUsMap" class="big-map"></div>
</div>
</div>
</div>
<footer class="footer footer-color-black">
<div class="container">
<nav class="pull-left">
<ul>
<li>
<a href="" data-scroll="true" data-id="#whoWeAre">
Inicio
</a>
</li>
<li>
<a href="" data-scroll="true" data-id="#buynow">
buynow
</a>
</li>
</ul>
</nav>
<div class="copyright">
© 2016 Fyolo
</div>
</div>
</footer>
</div> <!-- end wrapper -->
<!-- Core JS Files -->
<script src="js/jquery-2.2.4.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script src="js/jquery.bootstrap.js" type="text/javascript"></script>
<!-- file for adding vertical points where we activate the elements animation -->
<script type="text/javascript" src="js/jquery.waypoints.min.js"></script>
<!-- js library for devices recognition -->
<script type="text/javascript" src="js/modernizr.js"></script>
<!-- script for google maps -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD7cPHxDkDcq4nozX7j2XNRFNvlUs-nCaE&language=es"></script>
<!-- file where we handle all the script from the Rubik page -->
<script type="text/javascript" src="js/rubick_pres.js"></script>
<script type="text/javascript" src="js/presentation-page/jquery.sharrre.js"></script>
<?php include_once("../analyticstracking.php") ?>
</body>
</html><file_sep># midsa-website
Initial version, only for load libraries, test composer and test the deploy to Heroku<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
<script type="text/javascript" src="js/websocket_client.js"></script>
</head>
<body class="grey lighten-4" onload="javascript:WebSocketSupport()">
<div id="ws_support"></div>
<?php include 'inc/nav-transportista.php'; ?>
<div class="container">
<div class="card">
<div class="card-content">
<span class="card-title" style="font-weight: 400;">CAPTURAR INCIDENCIA</span>
<div class="col s12">
<div class="input-field col s12">
<p>¿Dónde ocurre la incidencia?</p>
<p>
<input name="group1" type="radio" id="test1" />
<label for="test1">Etiqueta</label>
</p>
<p>
<input name="group1" type="radio" id="test2" />
<label for="test2">Bulto</label>
</p>
<p>
<input class="with-gap" name="group1" type="radio" id="test3" />
<label for="test3">Ruta/Sucursal</label>
</p>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">attachment</i>
<label>Adjuntar evidencia</label>
<br><br>
<input type="file" class="validate" />
</div>
<div class="input-field col s12">
<i class="material-icons prefix">create</i>
<textarea id="textarea1" class="materialize-textarea"></textarea>
<label for="textarea1">Comentarios</label>
</div>
<div class="center">
<a href="transportista.php?capture=true" onclick="doSend(document.getElementById('msg').value)" class="btn btn-large waves-effect">Enviar <i class="material-icons right">send</i></a>
</div>
<div id="wrapper" style="display: none">
<div id="chatbox"></div>
<div id ="controls">
<label for="name"><b>Name</b></label>
<input name="chatname" type="text" id="chatname" size="67" placeholder="Type your name here" value="abc"/>
<input name="msg" type="text" id="msg" size="63" placeholder="Type your message here" value="abc" />
<input name="sendmsg" type="submit" id="sendmsg" value="Send" onclick="doSend(document.getElementById('msg').value)" />
</div>
</div>
</div>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".button-collapse").sideNav();
$('select').material_select();
});
</script>
</body>
</html><file_sep><!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Midsa - Online Store</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/carousel.css" rel="stylesheet">
</head>
<body>
<div class="container">
<?php include 'inc/header.php'; ?>
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1" class=""></li>
<li data-target="#myCarousel" data-slide-to="2" class=""></li>
</ol>
<div class="carousel-inner" role="listbox">
<div class="item active">
<div class="container">
<div class="carousel-caption">
<img src="img/Midsa.jpg">
</div>
</div>
</div>
<div class="item">
<div class="container">
<div class="carousel-caption">
<img src="img/HDPE-Midsa.jpg">
</div>
</div>
</div>
<div class="item">
<div class="container">
<div class="carousel-caption">
<img src="img/Sanalite-Midsa.jpg">
</div>
</div>
</div>
</div>
<a class="left carousel-control" href="#myCarousel" role="button"
data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"
aria-hidden="true"></span> <span class="sr-only">Previous</span>
</a> <a class="right carousel-control" href="#myCarousel"
role="button" data-slide="next"> <span
class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-lg-3">
<img src="img/UHMW-PE-Midsa.jpg">
<h4>UHMW-PE</h4>
<span class="text-muted"> Aplicaciones que van desde el
revestimiento de tolvas, partes expuestas al desgaste en bandas
transportadores, piezas maquinadas de acuerdo a sus necesidades.<br/><a class="btn btn-default" href="#" role="button">Vea mas »</a></span><hr>
</div>
<div class="col-xs-6 col-sm-6 col-lg-3">
<img src="img/QuickSilver-Midsa.jpg">
<h4>QuickSilver®</h4>
<span class="text-muted"> Recubrimiento para camiones que
facilitan la descarga de materiales viscosos, lodos y asfaltos.<br/><a class="btn btn-default" href="#" role="button">Vea mas »</a></span><hr>
</div>
<div class="col-xs-6 col-sm-6 col-lg-3">
<img src="img/Polipropileno-Midsa.jpg">
<h4>Polipropileno</h4>
<span class="text-muted">Placas y barras resistentes a quimicos
corrsivos.<br/><a class="btn btn-default" href="#" role="button">Vea mas »</a></span><hr>
</div>
<div class="col-xs-6 col-sm-6 col-lg-3">
<img src="img/Nylamid-Midsa.jpg">
<h4>Nylamid</h4>
<span class="text-muted"> Ayuda a eliminar la corrosión, a reducir
el consumo de energía, lubricantes y nivel de ruido y a mejorar
el desempeño y la vida útil de las partes y refacciones.<br/><a class="btn btn-default" href="nylon.php" role="button">Vea mas »</a></span><hr>
</div>
</div>
<br/>
<div class="row">
<div class="col-xs-6 col-sm-6 col-lg-3">
<img src="img/Acetal-POM-Midsa.jpg">
<h4>Acetal (POM)</h4>
<span class="text-muted">Posee una gran resistencia mecánica,
rigidez estructural, estabilidad dimensional y resilencia.<br/><a class="btn btn-default" href="#" role="button">Vea mas »</a></span><hr>
</div>
<div class="col-xs-6 col-sm-6 col-lg-3">
<img src="img/Polietileno-de-alta-densidad-MIDSA.jpg">
<h4>Polietileno de alta densidad</h4>
<span class="text-muted">Para usos diversos y partes mecánicas de
propósito general, anticorrosivo, firme y resistente para
aplicaciones en ambientes secos y húmedos.<br/><a class="btn btn-default" href="#" role="button">Vea mas »</a></span><hr>
</div>
<div class="col-xs-6 col-sm-6 col-lg-3">
<img src="img/Cortinas-Hawaianas-Midsa.jpg">
<h4><NAME></h4>
<span class="text-muted">Mantenga limpias sus áreas de trabajo,
alimentos, controla ruido, olores, polvo y humo.<br/><a class="btn btn-default" href="#" role="button">Vea mas »</a></span><hr>
</div>
<div class="col-xs-6 col-sm-6 col-lg-3">
<img src="img/PVC-Midsa.jpg">
<h4>PVC</h4>
<span class="text-muted">Barras y Placas para recibrimiento
anticorrosivo, fabricación de tanques y refacciones.<br/><a class="btn btn-default" href="#" role="button">Vea mas »</a></span><hr>
</div>
</div>
<?php include 'inc/footer.php';?>
</div>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
</head>
<body class="grey lighten-4">
<?php include 'inc/nav-transportista.php'; ?>
<div class="container">
<div class="card">
<div class="card-content">
<span class="card-title" style="font-weight: 400;">ESCANEAR BULTO</span>
<div class="col s12">
<div class="controls">
<div class="file-field input-field" style="height: 60px;">
<div class="btn" style="width: 100%;">
<span>ESCANEAR</span>
<input type="file" accept="image/*;capture=camera" />
</div>
</div>
<input type="hidden" name="input-stream_size" value="320" />
<input type="hidden" name="locator_patch-size" value="medium" />
<input type="hidden" name="numOfWorkers" value="1" />
</div>
<div id="interactive" class="viewport">
<canvas class="imgBuffer" width="300px" height="300px"></canvas>
<canvas class="drawingBuffer" width="300px" height="300px"></canvas>
<br clear="all">
</div>
<div class="center" id="result_strip">
</div>
<div class="center hidden" id="founded">
<a href="transportista.php?send=true" class="btn waves-effect">Enviar <i class="material-icons right">send</i></a>
</div>
</div>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script src="js/quagga.min.js"></script>
<script src="js/file_input.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".button-collapse").sideNav();
$('select').material_select();
});
</script>
</body>
</html><file_sep>var trialTimer;
function ShowTrialBackdrop(){
$('.trial-backdrop').fadeTo('slow', 0.99);
}
function HideTrialBackdrop(url) {
if (url){
var timeElapsed = new Date();
if (timeElapsed - trialTimer < 7000) {
window.setTimeout(function() { HideTrialBackdrop(url); }, 7000 - (timeElapsed - trialTimer));
return;
}
$('.trial-backdrop .loading').hide();
$('.trial-backdrop .finished').show();
$('.loading-gif').css({visibility: 'hidden'});
$('.trial-backdrop .trial-button-wrapper a').attr('href', url).removeClass('disabled');
$('#hdTrialUrl').val(url);
} else {
$('.trial-backdrop').fadeOut('slow');
$('.trial-backdrop .trial-button-wrapper a').attr('href', '#!').addClass('disabled');
}
}
$(function(){
$('.trial-backdrop').appendTo('body');
$('.trial-backdrop .trial-button-wrapper a').attr('href', '#!').addClass('disabled');
$('#trialPassword').on('keyup', function() {
$(this).addClass('touched');
if ($(this).val().length < 5) {
$(this).addClass('invalid')
$(this).removeClass('valid');
} else {
$(this).removeClass('invalid')
$(this).addClass('valid');
}
if ($('#trialPasswordConfirm').hasClass('touched')) {
if ($(this).hasClass('valid')) {
if ($(this).val() == $('#trialPasswordConfirm').val()) {
$('#trialPasswordConfirm').removeClass('invalid');
$('#trialPasswordConfirm').addClass('valid');
$('.trial-button-wrapper a').removeClass('disabled-invalid')
} else {
$('#trialPasswordConfirm').removeClass('valid');
$('#trialPasswordConfirm').addClass('invalid');
$('.trial-button-wrapper a').addClass('disabled-invalid');
}
} else {
$('#trialPasswordConfirm').removeClass('valid');
$('#trialPasswordConfirm').addClass('invalid');
$('.trial-button-wrapper a').addClass('disabled-invalid');
}
}
});
$('#trialPasswordConfirm').on('keyup', function(e) {
$(this).addClass('touched');
if ($(this).val() == $('#trialPassword').val() && $('#trialPassword').hasClass('valid')) {
$(this).removeClass('invalid');
$(this).addClass('valid');
$('.trial-button-wrapper a').removeClass('disabled-invalid');
} else {
$(this).addClass('invalid')
$(this).removeClass('valid');
$('.trial-button-wrapper a').addClass('disabled-invalid');
}
if (e.keyCode == 13) {
e.preventDefault();
if (!($('.trial-button-wrapper a').hasClass('disabled')) && !($('.trial-button-wrapper a').hasClass('disabled-invalid'))) goToTrial();
}
});
$("footer input[data-type], .trial-backdrop input[data-type]").each(function (i, el) {
$(el).data("placeholder", $(el).val());
$(el).on("focus", function () {
if ($(this).val() == $(this).data("placeholder")) {
$(this).val("");
$(this).attr('type', 'password');
}
}).on("blur", function () {
if ($(this).val() == "") {
$(this).val($(this).data("placeholder"));
$(this).attr('type', 'text');
$(this).removeClass('dirty');
} else {
$(this).addClass('dirty');
}
});
});
$('.trial-button-wrapper a').on('click', function(e) {
e.preventDefault();
if ($(this).is(':not(.disabled):not(.disabled-invalid)')) goToTrial();
return false;
});
window.adjustDisclaimerHeight = function() {
$('.disclaimer-iframe').height($('.disclaimer-iframe')[0].contentWindow.document.documentElement.scrollHeight);
}
$('.disclaimer-iframe').load(function() {
adjustDisclaimerHeight();
$('.disclaimer-iframe')[0].contentWindow.hideAreas();
});
$(window).resize(function() {
adjustDisclaimerHeight();
});
});
function goToTrial() {
$('.form-errors').html('');
if ($('#hdTrialUrl').val() == '') $('.form-errors').append('<div>No trial url found.</div>');
if ($('#trialPassword').val() != $('#trialPasswordConfirm').val()) $('.form-errors').append('<div>Passwords do not match.</div>');
if ($('#trialPassword').val().length < 5) $('.form-errors').append('<div>Password must be at least 5 characters.</div>');
if ($('.form-errors').html().length > 0) return;
var result, temp;
$('.trial-button-wrapper a').addClass('disabled');
temp = $.ajax({
type: 'POST',
dataType: 'json',
url: '/store/customercode/acdotcom/trialajaxhandler.asmx/TrialAssignedHandler',
contentType: 'application/json; charset=utf-8',
async: false,
data: JSON.stringify({
password: <PASSWORD>(),
storeUrl: $('<a>').prop('href', $('#hdTrialUrl').val()).prop('hostname')
})
}).responseText;
if (temp) {
result = JSON.parse(temp).d;
if (result) {
if (!result.Success) {
$('.form-errors').append('<div>' + result.Message + '</div>');
return
} else {
$('.trial-button-wrapper a').attr('href', result.Message);
location.href = result.Message;
}
}
}
}
$(function() {
$('.contact-us.fork').popover({
html: 'true',
content: '<ul class="contact-btn-list"><li><a href="/sellonline/contact">Online Store</a></li><li><a href="/sellinperson/contact">In Person</a></li></ul>',
placement: 'top'
});
});<file_sep><!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Midsa - Online Store</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/carousel.css" rel="stylesheet">
<link href="css/bootstrap-theme.css" rel="stylesheet">
</head>
<body>
<div class="container">
<?php include 'inc/header.php'; ?>
<div class="row" style="padding-top: 120px;">
<div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar">
<div class="list-group">
<a href="home.php" class="list-group-item">Catálogo</a>
<a href="nylon.php"
class="list-group-item" style="background: #cccccc;">Nylon</a>
<div style="padding: 10px; background: #336699;">
<b>> Nylamid M</b>
</div>
<div style="padding: 10px;">Nylamid XL</div>
<div style="padding: 10px;">Nylamid 901</div>
<div style="padding: 10px;">Nylamid SL</div>
<a href="polipropileno.php" class="list-group-item">Polipropileno</a>
<a href="polietileno" class="list-group-item">Polietileno / HDPE</a>
<a href="fenolicos" class="list-group-item">Fenolicos / Micartas</a>
<a href="acrilico" class="list-group-item">Acrilico</a> <a
href="cortinas" class="list-group-item">Cortinas Hawaianas</a> <a
href="policar" class="list-group-item">Policarbonato</a> <a
href="ptfe" class="list-group-item">Barras y Placas PTFE</a> <a
href="antiadherentes" class="list-group-item">Telas Antiadherentes</a>
<a href="acetal" class="list-group-item">Acetal (POM)</a> <a
href="sanalite" class="list-group-item">Sanalite</a> <a href="pvc"
class="list-group-item">PVC</a> <a href="antiestaticos"
class="list-group-item">Antiestaticos</a> <a href="especiales"
class="list-group-item">Especializados</a> <a href="stabilit"
class="list-group-item">Liner Panel (Recubrimientos de pared)</a>
</div>
</div>
<div class="col-xs-12 col-sm-9">
<p class="pull-right visible-xs">
<button type="button" class="btn btn-primary btn-xs"
data-toggle="offcanvas">Toggle nav</button>
</p>
<div>
<div class="row featurette">
<div class="col-md-7 col-md-push-5">
<h2>
Nylamid M
</h2>
<p class="lead">Nylon Natural. sin aditivos.
Combina una adecuada resistencia
mecánica, rigidez y dureza con una
buena resistencia al desgaste.
Aprobado para trabajar en contacto
con alimentos según la norma
NMX-E-202-1993-SCFI.</p>
<p>
Dimensiones:
<input type="text" class="form-control" placeholder="Alto" style="width: 100px;">
<input type="text" class="form-control" placeholder="Ancho" style="width: 100px;">
</p>
<p>Cantidad:
<button type="button" class="btn btn-default" onclick="clearCart();">-</button>
<button type="button" class="btn btn-default" onclick="addToCart();">+</button>
</p>
</div>
<div class="col-md-5 col-md-pull-7">
<img class="featurette-image img-responsive center-block"
data-src="holder.js/500x500/auto" alt="500x500"
src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj<KEY>Lz<KEY>ZXJqcy5jb20KKGMpIDIwMTItMjAxNSBJdmFuIE1hbG9waW5za3kgLSBodHR<KEY>
data-holder-rendered="true">
</div>
</div>
</div>
</div>
</div>
<?php include 'inc/footer.php';?>
</div>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type="text/javascript">
function addToCart() {
var badge = '<span class="badge">3</span>';
var node = document.createElement("span");
node.className = "badge";
node.id = "badge";
var textnode = document.createTextNode("3");
node.appendChild(textnode);
document.getElementById("carrito").appendChild(node);
}
function clearCart() {
document.getElementById("carrito").removeChild(document.getElementById("badge"));
}
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
<style type="text/css">
td, th {
padding: 5px;
border: 1px solid #ccc;
}
th {
text-align: center;
text-transform: uppercase;
background-color: #009688;
color: #fff;
}
</style>
</head>
<body>
<?php include 'inc/nav-admin.php'; ?>
<div class="container" style="width: 85%;">
<div class="row">
<div class="col s12">
<p>
<a href="admin.php">Administración</a>
<i class="material-icons grey-text" style="vertical-align: bottom;">keyboard_arrow_right</i>
Catálogo de Usuarios
</p>
<h5>Catálogo de Usuarios</h5>
<table class="table bordered striped">
<tr>
<th>ID</th>
<th>Usuario</th>
<th>Nombre/Apellidos</th>
<th>Tipo</th>
<th></th>
</tr>
<tr>
<td>1</td>
<td>eramirez</td>
<td><img src="img/esteban.jpg" style="height: 30px; width: 30px;" alt="" class="circle left"> Esteban Ramírez <a href="#!" class="secondary-content"><i class="material-icons">grade</i></a></td>
<td>Supervisor de piso</td>
<td><a href="#">Editar</a> | <a href="#">Bloquear</a></td>
</tr>
<tr>
<td>2</td>
<td>mlopez</td>
<td><img src="img/miriam.jpg" style="height: 30px; width: 30px;" alt="" class="circle left"> <NAME> <a href="#!" class="secondary-content"><i class="material-icons">grade</i></a></td>
<td>Supervisor de piso</td>
<td><a href="#">Editar</a> | <a href="#">Bloquear</a></td>
</tr>
<tr>
<td>3</td>
<td>cpeña</td>
<td><img src="img/claudia.jpg" style="height: 30px; width: 30px;" alt="" class="circle left"> <NAME></td>
<td>Tienda</td>
<td><a href="#">Editar</a> | <a href="#">Bloquear</a></td>
</tr>
<tr>
<td>4</td>
<td>rgarza</td>
<td><img src="img/ramiro.jpg" style="height: 30px; width: 30px;" alt="" class="circle left"> <NAME></td>
<td>Transportista</td>
<td><a href="#">Editar</a> | <a href="#">Bloquear</a> | <a href="#">re-asignar ruta</a></td>
</tr>
<tr>
<td>5</td>
<td>fmarquez</td>
<td><img src="img/francisco.jpg" style="height: 30px; width: 30px;" alt="" class="circle left"> <NAME></td>
<td>Transportista</td>
<td><a href="#">Editar</a> | <a href="#">Bloquear</a> | <a href="#">re-asignar ruta</a></td>
</tr>
</table>
<br>
<div class="center">
<a href="admin.php" class="btn waves-effect">Regresar</a>
</div>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".tab a").click(function() {
window.location.href = $(this).attr("href");
});
$(".button-collapse").sideNav();
$('.collapsible').collapsible();
});
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
<script type="text/javascript" src="js/websocket_client.js"></script>
</head>
<body class="grey lighten-4" onload="javascript:WebSocketSupport()">
<div id="ws_support"></div>
<div class="navbar-fixed">
<?php include 'inc/nav-supervisor.php'; ?>
</div>
<div class="container">
<h5>Hola <strong>Esteban</strong></h5>
<div class="row">
<div class="col s12 m6">
<div class="card">
<div class="card-content">
<span class="card-title" style="font-weight: 400;">Incidentes</span>
<ul class="collection" id="incidents">
<a href="incident1.php" class="collection-item avatar" id="incident1">
<i class="material-icons circle red" id="incident1-icon">warning</i>
<span class="title">Incidente 004</span>
<p><b>Sucursal APODACA</b><br>
Etiqueta viene dañada...
</p>
<span class="secondary-content" id="incident1-status"><b>REVISAR</b></span>
</a>
<a href="incident2.php" class="collection-item avatar" id="incident2">
<i class="material-icons circle red" id="incident2-icon">warning</i>
<span class="title">Incidente 012</span>
<p><b>Sucursal ESCOBEDO</b><br>
El bulto viene en condiciones sospechosas...
</p>
<span class="secondary-content" id="incident2-status"><b>REVISAR</b></span>
</a>
<a class="collection-item avatar grey lighten-3" id="incident3">
<i class="material-icons circle green" id="incident3-icon">done</i>
<span class="title" style="text-decoration: line-through;">Incidente 003</span>
<p>Tienda Aeropuerto<br>
Etiqueta viene dañada...
</p>
<span class="secondary-content" id="incident3-status">RESUELTO</span>
</a>
</ul>
</div>
</div>
<br><br>
</div>
<div class="col s12 m6">
<a href="misrutas.php" class="btn btn-large waves-effect" style="width: 100%;">
<i class="material-icons" style="float: left;">open_with</i> Supervisar rutas
</a>
<br><br>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".button-collapse").sideNav();
<?php if (isset($_REQUEST['close'])) { ?>
setTimeout(closeIncident(<?= $_REQUEST['close']?>), 3000);
<?php } ?>
});
function closeIncident(id) {
Materialize.toast('Incidente cerrado <i class="material-icons right">done</i>', 3000);
$("#incident" + id).addClass("grey lighten-3");
$("#incident" + id).attr("href", "#");
$("#incident" + id + "-status").html("RESUELTO");
$("#incident" + id + "-icon").addClass("green");
$("#incident" + id + "-icon").html("done");
}
</script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="favicon.ico">
<title>Traffic Manager - Demo</title>
<?php include 'inc/meta.php'; ?>
<?php include 'inc/styles.php'; ?>
</head>
<body class="grey lighten-4">
<?php include 'inc/nav-admin.php'; ?>
<div class="container">
<br>
<h5>Catálogo de Usuarios</h5>
<br>
<div class="section">
<div class="row">
<table class="table bordered striped">
<tr>
<th>ID</th>
<th>Usuario</th>
<th>Nombre/Apellidos</th>
<th>Tipo</th>
<th></th>
</tr>
<tr>
<td>1</td>
<td>eramirez</td>
<td><img src="img/esteban.jpg" style="height: 40px; width: 40px;" alt="" class="circle left"> <NAME> <a href="#!" class="secondary-content"><i class="material-icons">grade</i></a></td>
<td>Supervisor de piso</td>
<td><a href="#">Editar</a> | <a href="#">Bloquear</a></td>
</tr>
<tr>
<td>2</td>
<td>mlopez</td>
<td><img src="img/miriam.jpg" style="height: 40px; width: 40px;" alt="" class="circle left"> <NAME> <a href="#!" class="secondary-content"><i class="material-icons">grade</i></a></td>
<td>Supervisor de piso</td>
<td><a href="#">Editar</a> | <a href="#">Bloquear</a></td>
</tr>
<tr>
<td>3</td>
<td>cpeña</td>
<td><img src="img/claudia.jpg" style="height: 40px; width: 40px;" alt="" class="circle left"> <NAME></td>
<td>Tienda</td>
<td><a href="#">Editar</a> | <a href="#">Bloquear</a></td>
</tr>
<tr>
<td>4</td>
<td>rgarza</td>
<td><img src="img/ramiro.jpg" style="height: 40px; width: 40px;" alt="" class="circle left"> <NAME></td>
<td>Transportista</td>
<td><a href="#">Editar</a> | <a href="#">Bloquear</a> | <a href="#">re-asignar ruta</a></td>
</tr>
<tr>
<td>5</td>
<td>fmarquez</td>
<td><img src="img/francisco.jpg" style="height: 40px; width: 40px;" alt="" class="circle left"> <NAME></td>
<td>Transportista</td>
<td><a href="#">Editar</a> | <a href="#">Bloquear</a> | <a href="#">re-asignar ruta</a></td>
</tr>
</table>
<br>
<a href="admin.php" class="btn btn-large waves-effect">Regresar</a>
</div>
</div>
</div>
<?php include 'inc/scripts.php'; ?>
<script type="text/javascript">
$(document).ready(function() {
$(".button-collapse").sideNav();
$('.collapsible').collapsible();
});
</script>
</body>
</html>
|
3b1db636262f2df5ef80a53e24fb246f6c990f31
|
[
"JavaScript",
"Markdown",
"PHP"
] | 44
|
PHP
|
fernandolugo1/indautosoft-demos
|
42879210a6903842c58a7e6bf4aba008f811be40
|
9853691b265e6be996af0635c03a23ed5e081ec3
|
refs/heads/master
|
<file_sep>import csv, json
csvFilePath = 'Form Responses 1.csv'
csvFilePathOutput = 'ForVCards.csv'
with open(csvFilePathOutput, 'w') as csvOutput:
with open(csvFilePath) as csvFile:
csvReader = csv.DictReader(csvFile)
fieldnames = ['last_name',
'first_name',
'org',
'title',
'phone',
'email',
'website',
'street',
'city',
'p_code',
'country']
#
writer = csv.DictWriter(csvOutput, fieldnames=fieldnames)
writer.writeheader()
for rows in csvReader:
if rows['Duplicate?'] == 'Duplicate':
continue
state_central_private = rows['Are you doing government service / or working in private sector']
#{'first_name': rows['Name'] + " <NAME>", #
writer.writerow({'first_name': "JNVK " + rows['Name'] + " " + rows['Admission Year'] + "(" + rows['Admission Class'] + ") - " + rows['Passout Year'] + "(" +rows['Passout Class'] + ")",
'phone': rows['WhatsAppNumber'],
'email': rows['Email Address']})
<file_sep># JNV Kheda Alumni Details Collection and Maintenance
This project is about collecting and maintaining details of alumni of JNV Kheda. Currently working on a mini portal hosted as google web app and github pages. Google form has been taken down. Proof of concept is done as mentioned in [issue 5](https://github.com/dharmeshrchauhan/jnv-kheda-alumni/issues/5).
Note: As google form implementation is DEPRECATED, so following description is deprecated as well.
-
The collection form is implemented as google form. Edit link goes in email immediately after new entry or any changes as part of google form itself.
This repository contains following:
- Google script, that can be used to retrieve edit link for the form. It can be used to send to alumni to update the details.
- Python script to convert data collected in google form to the format required by the school.
- Python script to create csv compatible with csv2vcard.
## User Workflow

## Backend Workflow

<file_sep>function doPost(e) {
var params = JSON.stringify(e.parameter["name"]);
var output = HtmlService.createHtmlOutput("New entry stored to <a target='_top _blank' href='https://docs.google.com/spreadsheets/d/1<KEY>/edit?usp=sharing'>google sheet</a>");
var ss = SpreadsheetApp.openById('<KEY>');
var sheet = ss.getSheets()[0];
sheet.appendRow([e.parameter["name"], e.parameter["admyr"], e.parameter["admclass"], e.parameter["passoutyr"], e.parameter["passoutclass"], e.parameter["profession"]]);
return output;
}<file_sep>import csv, json
csvFilePath = 'Copy of Contact Information (Responses) - Form Responses 1.csv'
csvFilePathOutput = 'Alumni Data NVS RO Pune With PassoutYear- From Google Form responses.csv'
with open(csvFilePathOutput, 'w') as csvOutput:
with open(csvFilePath) as csvFile:
csvReader = csv.DictReader(csvFile)
fieldnames = ['Sr. No',
'JNV',
'Year of Admission',
'Class of Admission',
'Admission No.',
'Name of the Student',
'Highest Class Completed in JNV',
'Passout Year',
'Present Qualification',
'Present Profession',
'State/Central/Private',
'Mobile No',
'Email ID',
'Present Complete Address',
'Any Other Information']
#
writer = csv.DictWriter(csvOutput, fieldnames=fieldnames)
writer.writeheader()
srno = 1
for rows in csvReader:
if rows['Duplicate?'] == 'Duplicate':
continue
#profession student
state_central_private = ''
if rows['Occupation / work / Job with city of work'] == 'Student':
state_central_private = 'Student'
else:
state_central_private = rows['Are you doing government service / or working in private sector']
#state / central /private
state_central_private = rows['Are you doing government service / or working in private sector']
writer.writerow({'Sr. No': srno,
'JNV': 'KATHLAL',
'Year of Admission': rows['Admission Year'],
'Class of Admission': rows['Admission Class'],
'Admission No.': '',
'Name of the Student': rows['Name'],
'Highest Class Completed in JNV': rows['Passout Class'],
'Passout Year': rows['Passout Year'],
'Present Qualification': rows['Study/ Qualification '],
'Present Profession': rows['Occupation / work / Job with city of work'],
'State/Central/Private': state_central_private,
'Mobile No': rows['Contact Number '],
'Email ID': rows['Email Address'],
'Present Complete Address': rows['Address'],
'Any Other Information': rows['Any other information']})
srno += 1
#, 'KATHLAL', '', rows['<NAME>'
#create new json file and write data on it
#with open(jsonFilePath, 'w') as jsonFile:
#make it more readable and pretty
# jsonFile.write(json.dumps(data, indent=4))
<file_sep># JNV Kheda Alumni Details Collection and Maintenance
Note: As google form implementation is DEPRECATED.
-
The collection form is implemented as google form. Edit link goes in email immediately after new entry or any changes as part of google form itself.
This repository contains following:
- Google script, that can be used to retrieve edit link for the form. It can be used to send to alumni to update the details.
- Python script to convert data collected in google form to the format required by the school.
- Python script to create csv compatible with csv2vcard.
## User Workflow

## Backend Workflow

<file_sep>/*
* Global Variables
*/
// Form URL
var formURL = 'https://docs.google.com/forms/d/1LyEGJQqs7eJEvjNklXDa3MYatpjtooPFq3xsxGP6Lso/viewform';
// Sheet name used as destination of the form responses
var sheetName = 'Form Responses 1';
/*
* Name of the column to be used to hold the response edit URLs
* It should match exactly the header of the related column,
* otherwise it will do nothing.
*/
var columnName = 'Edit Url';
// Responses starting row
var startRow = 2;
function getEditResponseUrls(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
//ScriptApp.newTrigger('onFormSubmit').forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet()).onFormSubmit().create();
var form = FormApp.openByUrl(formURL);
/* ScriptApp.newTrigger('onFormSubmit1')
.forForm(form)
.onFormSubmit()
.create();*/
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var columnIndex = headers[0].indexOf(columnName);
var data = sheet.getDataRange().getValues();
for(var i = startRow-1; i < data.length; i++) {
if(data[i][0] != '' && data[i][columnIndex] == '') {
var timestamp = data[i][0];
var formSubmitted = form.getResponses(timestamp);
if(formSubmitted.length < 1) continue;
var editResponseUrl = formSubmitted[0].getEditResponseUrl();
var shorternedUrl = form.shortenFormUrl(editResponseUrl)
sheet.getRange(i+1, columnIndex+1).setValue(shorternedUrl);
}
}
}
// [START apps_script_triggers_onedit]
/**
* The event handler triggered when editing the spreadsheet.
* @param {Event} e The onEdit event.
*/
/*
function onEdit(e) {
// Set a comment on the edited cell to indicate when it was changed.
var range = e.range;
range.setNote('Last modified: ' + new Date());
}*/
// [END apps_script_triggers_onedit]
function onFormSubmit(e) {
var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName); //SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var columnIndex = headers[0].indexOf(columnName);
var range = e.range;
var rowNumber = range.getRow();
var form = FormApp.openByUrl(formURL);
var timestamp = range.getValues()[0][0]; //new Date(e.namedValues['Timestamp'][0]);
var formSubmitted = form.getResponses(timestamp);
// Get the Form response URL and add it to the Google Spreadsheet
var editResponseUrl = formSubmitted[0].getEditResponseUrl();
var shorternedUrl = form.shortenFormUrl(editResponseUrl)
sheet.getRange(rowNumber, columnIndex + 1).setValue(shorternedUrl)
}
|
c9015687f61476fcf601998c23c477d8701ade77
|
[
"Markdown",
"Python",
"JavaScript"
] | 6
|
Python
|
jnvkalumni/jnvkalumni.github.io
|
13427d86f37b5bdc27c681e6d2f7d6782b157411
|
911086bf5ae5f01e2124fc08ce04200c1a82e849
|
refs/heads/master
|
<file_sep>var AM = require('./../modules/account-manager');
var SMM = require('./../modules/system-message-manager');
var CMM = require('./../modules/chat-message-manager');
var SAH = require('./../modules/salt-and-hash');
module.exports = function(io, sessionStore, cookieParser) {
var SessionSockets = require('session.socket.io');
var sessionSockets = new SessionSockets(io, sessionStore, cookieParser, 'jsessionid');
var users = {}; // online users
sessionSockets.on('connection', function (err, socket, session) {
if(!session.user) return;
console.log('server>socket-chat: socket connect '+session.user.user)
users[session.user.user] = {
"socket": socket.id
};
// get system message
SMM.getSystemMessage(session.user.user, function(e, o){
if (e) {
console.log('server>socket-chat: error-get-system-message '+ e);
} else {
console.log('server>socket-chat: ok-get-system-message~');
io.sockets.socket(users[session.user.user].socket).emit("get-system-message", o);
// delete system message
SMM.delSystemMessage(session.user.user, function(e){
if(e){
console.log('server>socket-chat: error-del-system-message '+e)
} else {
console.log('server>socket-chat: ok-del-system-message')
}
})
}
})
// get chat message
CMM.getChatMessage(session.user.user, function(e, o){
if (e) {
console.log('server>socket-chat: error-get-chat-message '+ e);
} else {
console.log('server>socket-chat: ok-get-chat-message~');
io.sockets.socket(users[session.user.user].socket).emit("get-chat-message", o);
// delete chat message
CMM.delChatMessage(session.user.user, function(e){
if(e){
console.log('server>socket-chat: error-del-chat-message '+e)
} else {
console.log('server>socket-chat: ok-del-chat-message')
}
})
}
})
// get user data
function getAccountData(){
AM.getAccountData(session.user.user, function(e, o){
if (e) {
console.log('server>socket-chat: get-account-data '+ e);
} else {
console.log('server>socket-chat: get-account-data OK');
io.sockets.socket(users[session.user.user].socket).emit("send-account-data", o);
}
})
}
socket.on('get-account-data', function(){
getAccountData();
})
// create group, chaters join group chat
socket.on('create-group', function(data){
var _chatId = SAH.saltAndHash(data.grouptitle);
data.chatid = _chatId;
AM.addNewGroup(data, function(e, o){
console.log(o);
socket.emit('create-group-success', o);
})
})
// send comm message
socket.on('send-realtime-message', function(data){
// save chat message for offline user
for(var i=0; i<data.chaters.length; i++){
if(data.chaters[i] in users){
io.sockets.socket(users[data.chaters[i]].socket).join(data.chatid);
} else {
console.log('server > socket-chat : user is no online '+data.chaters[i])
CMM.setChatMessage(data, function(){
console.log('server > socket-chat: set chat message done~');
})
}
}
// send chat message for online user
console.log("Sending: " + data.message + " to " + data.chatid);
socket.broadcast.to(data.chatid).emit("get-realtime-message", data);
io.sockets.socket(users[data.sendmessageuser].socket).emit("get-realtime-message", data);
})
socket.on('disconnect', function(){
delete users[session.user.user];
console.log('server>socket-chat: socket disconnect user '+session.user.user);
})
socket.on('add-friend', function(data){
if (data.getmessageuser in users){
console.log("server>socket-chat: add: " + data.getmessageuser);
io.sockets.socket(users[data.getmessageuser].socket).emit("add-friend", data);
} else {
console.log("server>socket-chat: User does not online: " + data.getmessageuser);
// set system message
SMM.setSystemMessage(data, function(){
console.log('server>socket-chat: set system message done~');
})
}
})
socket.on('response-add-friend', function(data){
// create chat id
var _str = data.requireuser > data.responseuser ? (data.requireuser+data.responseuser) : (data.responseuser+data.requireuser);
var _chatId = SAH.saltAndHash(_str);
data.chatid = _chatId;
data.chaters = [data.requireuser, data.responseuser]
// save add friend
AM.addNewFriend(data, function(e, responseUserData, requireUser){
if (e) {
console.log('server>socket-chat: error-response-add-friend');
} else {
console.log('server>socket-chat: ok-response-add-friend '+responseUserData.user);
io.sockets.socket(users[requireUser].socket).emit("response-add-friend-success", {
type : 'comm',
message : 'add '+ responseUserData.user +' success~'
});
io.sockets.socket(users[responseUserData.user].socket).emit("response-add-friend-success", {
type : 'comm',
message : 'add '+ requireUser +' success~'
});
}
})
})
})
};
<file_sep>In Chat
========
nodeJS web chat app 网页聊天应用
<h2>Test</h2>
http://172.16.58.3/
<file_sep>/**
* Node.js chat
* Copyright (c) 2013 <NAME>
**/
var express = require('express');
var http = require('http');
var io = require('socket.io');
var app = express();
var redis = require('redis');
var RedisStore = require('connect-redis')(express);
var rClient = redis.createClient();
var sessionStore = new RedisStore({client:rClient});
var cookieParser = express.cookieParser('your secret here');
app.configure(function(){
app.set('port', 8080);
app.set('views', __dirname + '/app/server/views');
app.set('view engine', 'jade');
app.locals.pretty = true;
// app.use(express.favicon());
// app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(cookieParser);
app.use(express.session({store: sessionStore, key: 'jsessionid', secret: 'your secret here' }));
app.use(express.methodOverride());
app.use(require('stylus').middleware({ src: __dirname + '/app/public' }));
app.use(express.static(__dirname + '/app/public'));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
var server = http.createServer(app
).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
io = io.listen(server);
// 输出级别,不输出
io.set('log level', 1);
// 路由
require('./app/server/routers/chat-app')(app);
require('./app/server/router')(app);
// socket-room
require('./app/server/sockets/socket-room')(io, sessionStore, cookieParser);
<file_sep>$(document).ready(function() {
var host = window.location.host.split(':')[0];
var socket = io.connect('http://' + host);
var userName = $.cookie('user');
var accountData = null;
var $usersList = $('.users-list');
var $groupsList = $('.groups-list');
var $usersBoxBd = $('.users-box-bd');
var $chatExtend = $('.chat-extend');
var $chatExtendBd = $chatExtend.find('.chat-extend-bd');
var systemMessageCollection = []; // collect system message
/*{
user : 'memo'
, message : [
{
type : 'comm'
, getmessageuser : 'memo'
, sendmessageuser : 'double'
, isread : false
}
]
}*/
var chatMessageCollection = {}; // collect chat message
/*{
user : 'memo'
, message : {
user : [
{
getmessageuser : 'double'
, sendmessageuser : 'memo'
, message : 'hi~'
, isread : false
}
]
}
}*/
// get system message from mongodb
socket.on('get-system-message', function(data){
systemMessageCollection = systemMessageCollection.concat(data.message);
appendSystemMessage(data.message[i]);
})
// get chat message from mongodb
socket.on('get-chat-message', function(data){
chatMessageCollection = data.message;
for(k in data.message){
// append to message panel
appendChatMessage(data.message[k][data.message[k].length-1]);
}
})
// get account data when socket connect
socket.on('send-account-data', function(data){
accountData = data;
console.log(accountData);
var _htmlFriends = '';
for (var k in data.friends) {
_htmlFriends += '<li><a href="#none" data-chaters="' + data.friends[k].chaters + '" data-chatid="' + data.friends[k].chatid + '">' + k + '</a></li>';
}
$usersList.html(_htmlFriends);
var _htmlGroups = '';
for (var k in data.groups) {
_htmlGroups += '<li><a href="#none" data-chaters="' + data.groups[k].chaters + '" data-chatid="' + data.groups[k].chatid + '">' + k + '</a></li>';
}
$groupsList.html(_htmlGroups);
$usersBoxBd.find('a').click(function(e) {
e.preventDefault();
var $this = $(this);
$this.removeClass('active');
var chatTitle = $this.html();
var chatId = $this.data('chatid');
var chaters = $this.data('chaters');
var template = _.template(
$('script.template-chat-box').html()
);
$chatExtendBd.html(template({chatid: chatId, chaters: chaters}));
showChatMessageCollection(chatId);
showExtend(chatTitle);
})
})
function loadAccountData(){
socket.emit('get-account-data');
}
// show & init friends list
loadAccountData();
//get message
socket.on('get-realtime-message', function(data) {
console.log(data.message);
// store message by chatuser
var _chatId = data.chatid;
if(chatMessageCollection[_chatId] == undefined){
chatMessageCollection[_chatId] = [];
}
chatMessageCollection[_chatId].push(data);
// show message
if($('.chatid-input').val() == _chatId){ // if chat user is chating
if (data.sendmessageuser == userName) {
var _html = '<p class="send-message"><span>' + data.message + '</span></p>';
} else {
var _html = '<p class="get-message"><span>' + data.message + '</span></p>';
}
$('.chat-message-box').append(_html);
// message box keep scroll to bottom
if($('.chat-box-bd').css('overflow-y') == 'auto'){
$('.chat-box-bd').scrollTop($('.chat-message-box').height());
}
} else {
playMessageSound();
}
// append to message panel
appendChatMessage(data);
})
socket.on('add-friend', function(data){
playMessageSound();
systemMessageCollection.push(data);
appendSystemMessage(data)
})
socket.on('response-add-friend-success', function(data) {
loadAccountData();
playMessageSound();
systemMessageCollection.push(data);
appendSystemMessage(data)
})
socket.on('create-group-success', function(o){
loadAccountData();
})
// show search-box
$('.j-search-friend-btn').on('click', function(){
showExtend('Search');
if($('.search-box').length == 0){
var template = _.template(
$('script.template-search-box').html()
);
$chatExtendBd.html(template());
}
$('#search-form').submit(function(e){
e.preventDefault();
var user = $('#search-user').val();
$.ajax({
type: 'get',
url: '/search-friend',
data: { user: user },
success : function(response, status, xhr, $form){
if (status == 'success'){
console.log('search success~~~')
var template = _.template(
$('script.search-friends-list').html()
);
$('.search-list').html(template(response));
$('.search-list').removeClass('hide');
$('.search-list .add').click(function(){
var getmessageuser = $(this).siblings('.user').html();
socket.emit('add-friend', {
type : 'add-friend'
, getmessageuser : getmessageuser
, sendmessageuser : userName
});
$(this).remove();
})
}
},
error : function(e){
console.log('search fail~~~')
}
})
})
})
// show create group box
$('.j-show-create-group').click(function(){
showExtend('Create Group');
var template = _.template(
$('script.template-select-friend').html()
);
$chatExtendBd.html(template({friends:accountData.friends}));
})
// create group
$(document).delegate('#group-select-form', 'submit', function(e){
e.preventDefault();
var _arr = [userName];
var _groupTitle = $('.select-friend-box-ft').find('.group-title').val();
$('.select-friend-box-bd').find( ":checked" ).each(function(){
_arr.push($(this).val());
})
// create-group
socket.emit('create-group', {
'grouptitle': _groupTitle
, 'chaters': _arr
, 'user': userName
})
})
// send message
$(document).delegate(".chat-form", 'submit', function(e) {
e.preventDefault();
var message = $('.message-input').val();
// stop empty message
if($.trim(message) == '') return;
var _chatId = $('.chatid-input').val();
var _chaters = $('.chaters-input').val().split(',');
var _chatTitle = $('.chat-extend-title').html();
socket.emit('send-realtime-message', {
'message' : message
, 'sendmessageuser' : userName
, 'chatid' : _chatId
, 'chaters' : _chaters
, 'chattitle' : _chatTitle
})
$('.message-input').val('');
})
// close extend-box
$(document).delegate('.j-extend-box-close', 'click', function(){
$(this).parents('.extend-box').fadeOut().delay(1000).remove();
})
// get indexedDB message 10 item per require
$(document).delegate('.get-indexeddb-message', 'click', function(){
var currentMessageLength = $('.chat-message-box').find('.send-message, .get-message').length;
var _chatId = $('.chatid-input').val();
})
// show message detail
$(document).delegate('.messages-item', 'click', function(){
showExtend('System Message');
$chatExtendBd.html('');
var _type = $(this).data('type');
switch(_type){
case 'chat':
var _chatId = $(this).data('chatid');
var _chaters = $(this).data('chaters');
var _chatTitle = $(this).find('.item-title').html();
if($('.chat-extend .chat-box').length == 0){
var template = _.template(
$('script.template-chat-box').html()
);
$chatExtendBd.html(template({chatid:_chatId, chaters: _chaters}));
}
showChatMessageCollection(_chatId);
showExtend(_chatTitle);
break;
case 'add-friend': // system add friend message
var _data = {sendmessageuser: $(this).data('user')}
var template = _.template(
$('script.add-friend-box').html()
);
$chatExtendBd.prepend(template(_data));
$('.add-friend-yes').click(function(){
var requireuser = $(this).siblings('.j-require-user').html();
socket.emit('response-add-friend', {
type: 'add-friend'
, requireuser: requireuser
, responseuser: userName
})
console.log('agree add~');
$(this).parents('.extend-box').fadeOut().remove();
})
$('.add-friend-no').click(function(){
console.log('disagree add~');
$(this).parents('.extend-box').fadeOut().remove();
})
$(this).remove();
break;
case 'comm': // system common message
default:
var _message = $(this).data('message');
var _data = {message: _message}
var template = _.template(
$('script.comm-box').html()
);
$chatExtendBd.prepend(template(_data));
$(this).remove();
break;
}
})
// hide chat-extend panel
$('.chat-extend-hd .glyphicon-chevron-right').click(function(){
hideExtend();
})
$('.chat-extend').hammer().on('dragright', function(){
hideExtend();
})
// panel control button
$('.chat-main-ft .glyphicon-comment').click(function(){
$('.chat-main-bd .main-box').addClass('hide');
$('.chat-main-bd .messages-box').removeClass('hide');
$('.chat-main-ft .glyphicon').removeClass('active');
$('.chat-main-ft .glyphicon-comment').addClass('active');
})
$('.chat-main-ft .glyphicon-user').click(function(){
$('.chat-main-bd .main-box').addClass('hide');
$('.chat-main-bd .users-box').removeClass('hide');
$('.chat-main-ft .glyphicon').removeClass('active');
$('.chat-main-ft .glyphicon-user').addClass('active');
})
$('.chat-main-ft .glyphicon-home').click(function(){
location.href = '/home';
})
/* extend methods */
// read chat message from var chatMessageCollection
function showChatMessageCollection(user){
var _html = '<p class="message-tip"><button class="btn get-indexeddb-message">more message</button></p>';
if(!(user in chatMessageCollection)){
$('.chat-message-box').html(_html);
return;
}
for(var i=0; i<chatMessageCollection[user].length; i++){
if (chatMessageCollection[user][i].sendmessageuser == userName) {
_html += '<p class="send-message"><span>' + chatMessageCollection[user][i].message + '</span></p>';
} else {
_html += '<p class="get-message"><span>' + chatMessageCollection[user][i].message + '</span></p>';
}
}
$('.chat-message-box').html(_html);
// message box keep scroll to bottom on pc
if($('.chat-box-bd').css('overflow-y') == 'auto'){
$('.chat-box-bd').scrollTop($('.chat-message-box').height());
}
}
// chat message append to message panel
function appendChatMessage(data){
var _chatUser = (data.sendmessageuser == userName ? data.getmessageuser : data.sendmessageuser);
if($('.messages-item[data-chatid="'+data.chatid+'"]').length > 0){
$('.messages-item[data-chatid="'+data.chatid+'"]').find('.item-content').html(data.sendmessageuser+': '+data.message);
} else {
var _html = '<div class="messages-item" data-type="chat" data-chaters="'+data.chaters+'" data-chatid="'+data.chatid+'">';
_html += '<h3 class="item-title">'+data.chattitle+'</h3>'
_html += '<p class="item-content">'+data.sendmessageuser+': '+data.message+'</p>'
_html += '</div>';
$('.messages-box').prepend(_html);
}
}
// system message append to message panel
function appendSystemMessage(data){
var _type = data.type;
switch(_type){
case 'add-friend':
var _html = '<div class="messages-item" data-type="'+data.type+'" data-user="'+data.sendmessageuser+'">';
_html += '<h3 class="item-title">'+data.sendmessageuser+'</h3>'
_html += '<p class="item-content">add friend require~</p>'
_html += '</div>';
$('.messages-box').prepend(_html);
break;
case 'comm':
default:
var _html = '<div class="messages-item" data-type="'+data.type+'" data-message="'+data.message+'">';
_html += '<h3 class="item-title">System Message</h3>'
_html += '<p class="item-content">'+data.message+'</p>'
_html += '</div>';
$('.messages-box').prepend(_html);
break;
}
}
// for mobile device
function showExtend(title){
$('.chat-extend-title').html(title);
$('.chat-extend').animate({
width: '100%'
})
}
// for mobile device
function hideExtend(){
$('.chat-extend').animate({
width: 0
}).find('.chat-extend-bd').html('');
}
// play message sound
function playMessageSound(){
document.getElementById('chat-get-message-sound').play();
}
})
|
13dffadba64079c57bc9d47a8d0af05d396c3114
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
Francispp/In-Chat
|
675fd69ae3dee11905ed296e16e524a78ae2e18b
|
5573cc880620c3d682c4f202a4ea2133c268d9c8
|
refs/heads/master
|
<file_sep>#include <fstream>
#include "ns3/core-module.h"
#include "ns3/internet-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-apps-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/ipv4-static-routing-helper.h"
#include "ns3/ipv4-routing-table-entry.h"
#include "ns3/netanim-module.h"
#include "ns3/applications-module.h"
#include "ns3/flow-monitor-helper.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE ("DOS");
void TearDownLink (Ptr<Node> nodeA, Ptr<Node> nodeB, uint32_t interfaceA, uint32_t interfaceB)
{
nodeA->GetObject<Ipv4> ()->SetDown (interfaceA);
nodeB->GetObject<Ipv4> ()->SetDown (interfaceB);
}
/*
class DdosApp : public App
{
public:
//static TypeId GetTypeId ();
DdosApp ();
virtual ~DdosApp ();
// @brief Actually send packet
void
SendPacket ();
protected:
// from App
virtual void
StartApplication ();
virtual void
StopApplication ();
void
DelayedStop ();
private:
UniformVariable m_rand; ///< @brief nonce generator
UniformVariable m_jitter; ///< @brief nonce generator
uint32_t m_seq; ///< @brief currently requested sequence number
EventId m_nextSendEvent;
Time m_lifetime;
Time m_avgGap; ///< @brief average gap between interests (should be short, but still should be, otherwise simulation will never finishes)
// default interest
// InterestHeader m_defaultInterest;
Name m_prefix;
bool m_evilBit;
bool m_dataBasedLimit;
};
TypeId
DdosApp::GetTypeId ()
{
static TypeId tid = TypeId ("DdosApp")
.SetParent<App> ()
.AddConstructor<DdosApp> ()
.AddAttribute ("AvgGap", "AverageGap",
StringValue ("1ms"),
MakeTimeAccessor (&DdosApp::m_avgGap),
MakeTimeChecker ())
.AddAttribute ("Prefix","Name of the Interest",
StringValue ("/"),
MakeNameAccessor (&DdosApp::m_prefix),
MakeNameChecker ())
.AddAttribute ("LifeTime","Interest lifetime",
StringValue ("1s"),
MakeTimeAccessor (&DdosApp::m_lifetime),
MakeTimeChecker ())
.AddAttribute ("Evil", "Evil bit",
BooleanValue (false),
MakeBooleanAccessor (&DdosApp::m_evilBit),
MakeBooleanChecker ())
.AddAttribute ("DataBasedLimits", "Calculate frequency based on how many data packets can be returned",
BooleanValue (true),
MakeBooleanAccessor (&DdosApp::m_dataBasedLimit),
MakeBooleanChecker ())
;
return tid;
}
DdosApp::DdosApp ()
: m_rand (0, std::numeric_limits<uint32_t>::max ())
, m_jitter (0,1)
, m_seq (0)
{
}
DdosApp::~DdosApp ()
{
}
void
DdosApp::SendPacket ()
{
m_seq++;
// send packet
Ptr<NameComponents> nameWithSequence = Create<NameComponents> (m_prefix);
nameWithSequence->appendSeqNum (m_seq);
Ptr<Interest> interest = Create<Interest> ();
interest->SetNonce (m_rand.GetValue ());
interest->SetName (nameWithSequence);
interest->SetInterestLifetime (m_lifetime);
NS_LOG_INFO ("> Interest for " << m_seq << ", lifetime " << m_lifetime.ToDouble (Time::S) << "s");
m_face->ReceiveInterest (interest);
m_transmittedInterests (interest, this, m_face);
// std::cout << "Size: " << packet->GetSize () << std::endl;
// NS_LOG_DEBUG (m_avgGap+MilliSeconds (m_rand.GetValue ()));
Time nextTime = m_avgGap + Time::FromDouble (m_jitter.GetValue (), Time::US);
NS_LOG_DEBUG ("next time: " << nextTime.ToDouble (Time::S) << "s");
m_nextSendEvent = Simulator::Schedule (nextTime,
&DdosApp::SendPacket, this);
}
void
DdosApp::StartApplication ()
{
// calculate outgoing rate and set Interest generation rate accordingly
double sumOutRate = 0.0;
Ptr<Node> node = GetNode ();
for (uint32_t deviceId = 0; deviceId < node->GetNDevices (); deviceId ++)
{
Ptr<PointToPointNetDevice> device = DynamicCast<PointToPointNetDevice> (node->GetDevice (deviceId));
if (device == 0)
continue;
DataRateValue dataRate; device->GetAttribute ("DataRate", dataRate);
sumOutRate += (dataRate.Get ().GetBitRate () / 8);
}
double maxInterestTo = sumOutRate / 40;
double maxDataBack = sumOutRate / 1146;
if (m_evilBit)
{
if (m_dataBasedLimit)
{
m_avgGap = Seconds (0.1 / maxDataBack);
}
else
{
m_avgGap = Seconds (1 / maxInterestTo);
}
// std::cout << "evil Gap: " << m_avgGap.ToDouble (Time::S) << "s\n";
}
else
{
// m_avgGap = Seconds (2 * 1 / maxDataBack); // request 50% of maximum link capacity
// std::cout << "good Gap: " << m_avgGap.ToDouble (Time::S) << "s\n";
}
App::StartApplication ();
SendPacket ();
}
void
DdosApp::StopApplication ()
{
m_nextSendEvent.Cancel ();
// std::cerr << "# references before delayed stop: " << m_face->GetReferenceCount () << std::endl;
Simulator::Schedule (Seconds (10.0), &DdosApp::DelayedStop, this);
}
void
DdosApp::DelayedStop ()
{
// std::cerr << "# references after delayed stop: " << m_face->GetReferenceCount () << std::endl;
App::StopApplication ();
}
*/
int main (int argc, char **argv)
{
bool verbose = false;
bool printRoutingTables = true;
bool showPings = false;
std::string SplitHorizon ("SplitHorizon");
CommandLine cmd;
cmd.AddValue ("verbose", "turn on log components", verbose);
cmd.AddValue ("printRoutingTables", "Print routing tables at 30, 60 and 90 seconds", printRoutingTables);
cmd.AddValue ("showPings", "Show Ping6 reception", showPings);
cmd.AddValue ("splitHorizonStrategy", "Split Horizon strategy to use (NoSplitHorizon, SplitHorizon, PoisonReverse)", SplitHorizon);
cmd.Parse (argc, argv);
if (verbose)
{
LogComponentEnableAll (LogLevel (LOG_PREFIX_TIME | LOG_PREFIX_NODE));
LogComponentEnable ("RipSimpleRouting", LOG_LEVEL_INFO);
LogComponentEnable ("Rip", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv4Interface", LOG_LEVEL_ALL);
LogComponentEnable ("Icmpv4L4Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("Ipv4L3Protocol", LOG_LEVEL_ALL);
LogComponentEnable ("ArpCache", LOG_LEVEL_ALL);
LogComponentEnable ("V4Ping", LOG_LEVEL_ALL);
}
if (SplitHorizon == "NoSplitHorizon")
{
Config::SetDefault ("ns3::Rip::SplitHorizon", EnumValue (RipNg::NO_SPLIT_HORIZON));
}
else if (SplitHorizon == "SplitHorizon")
{
Config::SetDefault ("ns3::Rip::SplitHorizon", EnumValue (RipNg::SPLIT_HORIZON));
}
else
{
Config::SetDefault ("ns3::Rip::SplitHorizon", EnumValue (RipNg::POISON_REVERSE));
}
NS_LOG_INFO ("Create nodes.");
Ptr<Node> server = CreateObject<Node> ();
Names::Add ("ServerNode", server);
Ptr<Node> R1 = CreateObject<Node> ();
Names::Add ("Router1", R1);
Ptr<Node> R2 = CreateObject<Node> ();
Names::Add ("Router2", R2);
Ptr<Node> g1 = CreateObject<Node> ();
Names::Add ("GoodNode1", g1);
Ptr<Node> g2 = CreateObject<Node> ();
Names::Add ("GoodNode2", g2);
Ptr<Node> g3= CreateObject<Node> ();
Names::Add ("GoodNode3", g3);
Ptr<Node> e1= CreateObject<Node> ();
Names::Add ("BadNode1", e1);
Ptr<Node> e2= CreateObject<Node> ();
Names::Add ("BadNode2", e2);
Ptr<Node> e3= CreateObject<Node> ();
Names::Add ("BadNode3", e3);
NodeContainer net1 (server, R1);
NodeContainer net2 (R1, R2);
NodeContainer net3 (R2, g1);
NodeContainer net4 (R2, g2);
NodeContainer net5 (R2, g3);
NodeContainer net6 (R1, e1);
NodeContainer net7 (R1, e2);
NodeContainer net8 (R2, e3);
NodeContainer routers (R1, R2);
NodeContainer nodes (server, g1, g2, g3);
NodeContainer goodNodes (g1,g2,g3);
NodeContainer badNodes (e1,e2,e3);
NS_LOG_INFO ("Create channels.");
CsmaHelper csmaG, csmaE, csmaR;
csmaR.SetChannelAttribute ("DataRate", StringValue ("200Mbps"));
csmaR.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (1)));
csmaG.SetChannelAttribute ("DataRate", StringValue ("60Mbps"));
csmaG.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
csmaE.SetChannelAttribute ("DataRate", StringValue ("100Mbps"));
csmaE.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (2)));
NetDeviceContainer ndc1 = csmaR.Install (net1);
NetDeviceContainer ndc2 = csmaR.Install (net2);
NetDeviceContainer ndc3 = csmaG.Install (net3);
NetDeviceContainer ndc4 = csmaG.Install (net4);
NetDeviceContainer ndc5 = csmaG.Install (net5);
NetDeviceContainer ndc6 = csmaE.Install (net6);
NetDeviceContainer ndc7 = csmaE.Install (net7);
NetDeviceContainer ndc8 = csmaE.Install (net8);
NS_LOG_INFO ("Create IPv4 and routing");
RipHelper ripRouting;
// Rule of thumb:
// Interfaces are added sequentially, starting from 0
// However, interface 0 is always the loopback...
ripRouting.ExcludeInterface (R1, 1);
ripRouting.ExcludeInterface (R1, 3);
ripRouting.ExcludeInterface (R1, 4);
ripRouting.ExcludeInterface (R2, 2);
ripRouting.ExcludeInterface (R2, 3);
ripRouting.ExcludeInterface (R2, 4);
ripRouting.ExcludeInterface (R2, 5);
ripRouting.SetInterfaceMetric (R1, 1, 8);
ripRouting.SetInterfaceMetric (R1, 2, 10);
ripRouting.SetInterfaceMetric (R1, 3, 10);
Ipv4ListRoutingHelper listRH;
listRH.Add (ripRouting, 0);
// Ipv4StaticRoutingHelper staticRh;
// listRH.Add (staticRh, 5);
InternetStackHelper internet;
internet.SetIpv6StackInstall (false);
internet.SetRoutingHelper (listRH);
internet.Install (routers);
InternetStackHelper internetNodes;
internetNodes.SetIpv6StackInstall (false);
internetNodes.Install (nodes);
internetNodes.Install (badNodes);
// Assign addresses.
// The source and destination networks have global addresses
// The "core" network just needs link-local addresses for routing.
// We assign global addresses to the routers as well to receive
// ICMPv6 errors.
NS_LOG_INFO ("Assign IPv4 Addresses.");
Ipv4AddressHelper ipv4;
ipv4.SetBase (Ipv4Address ("10.0.0.0"), Ipv4Mask ("255.255.255.0"));
Ipv4InterfaceContainer iic1 = ipv4.Assign (ndc1);
ipv4.SetBase (Ipv4Address ("10.0.1.0"), Ipv4Mask ("255.255.255.0"));
Ipv4InterfaceContainer iic2 = ipv4.Assign (ndc2);
ipv4.SetBase (Ipv4Address ("10.0.2.0"), Ipv4Mask ("255.255.255.0"));
Ipv4InterfaceContainer iic3 = ipv4.Assign (ndc3);
ipv4.SetBase (Ipv4Address ("10.0.3.0"), Ipv4Mask ("255.255.255.0"));
Ipv4InterfaceContainer iic4 = ipv4.Assign (ndc4);
ipv4.SetBase (Ipv4Address ("10.0.4.0"), Ipv4Mask ("255.255.255.0"));
Ipv4InterfaceContainer iic5 = ipv4.Assign (ndc5);
ipv4.SetBase (Ipv4Address ("10.0.5.0"), Ipv4Mask ("255.255.255.0"));
Ipv4InterfaceContainer iic6 = ipv4.Assign (ndc6);
ipv4.SetBase (Ipv4Address ("10.0.6.0"), Ipv4Mask ("255.255.255.0"));
Ipv4InterfaceContainer iic7 = ipv4.Assign (ndc7);
ipv4.SetBase (Ipv4Address ("10.0.7.0"), Ipv4Mask ("255.255.255.0"));
Ipv4InterfaceContainer iic8 = ipv4.Assign (ndc8);
Ptr<Ipv4StaticRouting> staticRouting;
staticRouting = Ipv4RoutingHelper::GetRouting <Ipv4StaticRouting> (server->GetObject<Ipv4> ()->GetRoutingProtocol ());
staticRouting->SetDefaultRoute ("10.0.0.2", 1 );
staticRouting = Ipv4RoutingHelper::GetRouting <Ipv4StaticRouting> (g1->GetObject<Ipv4> ()->GetRoutingProtocol ());
staticRouting->SetDefaultRoute ("10.0.2.1", 1 );
staticRouting = Ipv4RoutingHelper::GetRouting <Ipv4StaticRouting> (g2->GetObject<Ipv4> ()->GetRoutingProtocol ());
staticRouting->SetDefaultRoute ("10.0.3.1", 1 );
staticRouting = Ipv4RoutingHelper::GetRouting <Ipv4StaticRouting> (g3->GetObject<Ipv4> ()->GetRoutingProtocol ());
staticRouting->SetDefaultRoute ("10.0.4.1", 1 );
staticRouting = Ipv4RoutingHelper::GetRouting <Ipv4StaticRouting> (e1->GetObject<Ipv4> ()->GetRoutingProtocol ());
staticRouting->SetDefaultRoute ("10.0.5.1", 1 );
staticRouting = Ipv4RoutingHelper::GetRouting <Ipv4StaticRouting> (e2->GetObject<Ipv4> ()->GetRoutingProtocol ());
staticRouting->SetDefaultRoute ("10.0.6.1", 1 );
staticRouting = Ipv4RoutingHelper::GetRouting <Ipv4StaticRouting> (e3->GetObject<Ipv4> ()->GetRoutingProtocol ());
staticRouting->SetDefaultRoute ("10.0.7.1", 1 );
if (printRoutingTables)
{
RipHelper routingHelper;
Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper> (&std::cout);
routingHelper.PrintRoutingTableAt (Seconds (10.0), R1, routingStream);
routingHelper.PrintRoutingTableAt (Seconds (10.0), R2, routingStream);
routingHelper.PrintRoutingTableAt (Seconds (50.0), R1, routingStream);
routingHelper.PrintRoutingTableAt (Seconds (50.0), R2, routingStream);
//routingHelper.PrintRoutingTableAt (Seconds (90.0), R1, routingStream);
//routingHelper.PrintRoutingTableAt (Seconds (90.0), R2, routingStream);
}
NS_LOG_INFO ("Create Applications.");
uint16_t port = 4000;
UdpServerHelper serverHelper (port);
ApplicationContainer apps = serverHelper.Install (server);
apps.Start (Seconds (5.0));
apps.Stop (Seconds (110.0));
/*Check here for bugs*/
Address serverAddress = Address(iic1.GetAddress(0));
uint32_t MaxPacketSize = 1024;
Time interPacketInterval = Seconds (3); //20 packets per second
uint32_t maxPacketCount = 1200;
UdpClientHelper client (serverAddress, port);
client.SetAttribute ("MaxPackets", UintegerValue (maxPacketCount));
client.SetAttribute ("Interval", TimeValue (interPacketInterval));
client.SetAttribute ("PacketSize", UintegerValue (MaxPacketSize));
apps = client.Install (g1);
apps.Start (Seconds (1.0));
apps.Stop (Seconds (60.0));
apps = client.Install (g2);
apps.Start (Seconds (15.0));
apps.Stop (Seconds (60.0));
apps = client.Install (g3);
apps.Start (Seconds (30.0));
apps.Stop (Seconds (60.0));
Time interPacketIntervalB1 = Seconds (0.0006);
Time interPacketIntervalB = Seconds (0.0006);
uint32_t maxPacketCountB = 12000;
UdpClientHelper clientB (serverAddress, port);
clientB.SetAttribute ("MaxPackets", UintegerValue (maxPacketCountB));
clientB.SetAttribute ("Interval", TimeValue (interPacketIntervalB));
clientB.SetAttribute ("PacketSize", UintegerValue (MaxPacketSize));
apps = clientB.Install (e1);
apps.Start (Seconds (10.0));
apps.Stop (Seconds (60.0));
apps = clientB.Install (e2);
apps.Start (Seconds (10.0));
apps.Stop (Seconds (60.0));
UdpClientHelper clientB1 (serverAddress, port);
clientB1.SetAttribute ("MaxPackets", UintegerValue (maxPacketCountB));
clientB1.SetAttribute ("Interval", TimeValue (interPacketIntervalB1));
clientB1.SetAttribute ("PacketSize", UintegerValue (MaxPacketSize));
apps = clientB1.Install (e3);
apps.Start (Seconds (30.0));
apps.Stop (Seconds (60.0));
/*
uint32_t packetSize = 1024;
Time interPacketInterval = Seconds (1.0);
V4PingHelper ping ("10.0.0.1");
ping.SetAttribute ("Interval", TimeValue (interPacketInterval));
ping.SetAttribute ("Size", UintegerValue (packetSize));
if (showPings)
{
ping.SetAttribute ("Verbose", BooleanValue (true));
}
ApplicationContainer app1 = ping.Install (g1);
app1.Start (Seconds (1.0));
app1.Stop (Seconds (110.0));
ApplicationContainer app2 = ping.Install (g2);
app2.Start (Seconds (10.0));
app2.Stop (Seconds (110.0));
ApplicationContainer app3 = ping.Install (g3);
app3.Start (Seconds (20.0));
app3.Stop (Seconds (110.0));
*/
//AsciiTraceHelper ascii;
//csma.EnableAsciiAll (ascii.CreateFileStream ("rip-simple-routing.tr"));
//csma.EnablePcapAll ("rip-simple-routing", true);
//Simulator::Schedule (Seconds (40), &TearDownLink, b, d, 3, 2);
/* Now, do the actual simulation. */
/*
AppHelper evilAppHelper ("DdosApp");
evilAppHelper.SetAttribute ("Evil", BooleanValue (true));
evilAppHelper.SetAttribute ("LifeTime", StringValue ("1s"));
evilAppHelper.SetAttribute ("DataBasedLimits", BooleanValue (true));
AppHelper goodAppHelper ("DdosApp");
goodAppHelper.SetAttribute ("LifeTime", StringValue ("1s"));
goodAppHelper.SetAttribute ("DataBasedLimits", BooleanValue (true));
ApplicationContainer goodApp;
goodAppHelper.SetAttribute ("AvgGap", TimeValue (Seconds (1.100 / maxNonCongestionShare)));
goodApp.Add (goodAppHelper.Install (g1));
goodApp.Add (goodAppHelper.Install (g2));
goodApp.Add (goodAppHelper.Install (g3));
UniformVariable rand (0, 1);
goodApp.Start (Seconds (0.0) + Time::FromDouble (rand.GetValue (), Time::S));
*/
Ptr<FlowMonitor> flowMonitor;
FlowMonitorHelper flowHelper;
flowMonitor = flowHelper.InstallAll();
AnimationInterface anim ("animation.xml");
anim.SetConstantPosition (net1.Get(0), 50, 10);
anim.SetConstantPosition (net2.Get(0), 40, 20);
anim.SetConstantPosition (net2.Get(1), 35, 30);
anim.SetConstantPosition (net3.Get(1), 10, 50);
anim.SetConstantPosition (net4.Get(1), 25, 50);
anim.SetConstantPosition (net5.Get(1), 35, 50);
anim.SetConstantPosition (net6.Get(1), 60, 10);
anim.SetConstantPosition (net7.Get(1), 50, 30);
anim.SetConstantPosition (net8.Get(1), 45, 50);
AsciiTraceHelper ascii;
csmaR.EnableAsciiAll (ascii.CreateFileStream ("dos-attack.tr"));
csmaR.EnablePcapAll ("dos-attack", true);
NS_LOG_INFO ("Run Simulation.");
Simulator::Stop (Seconds (80.0));
Simulator::Run ();
flowMonitor->SerializeToXmlFile("dosFlowMonitor.xml", true, true);
Simulator::Destroy ();
NS_LOG_INFO ("Done.");
}
|
b4648c337a3ecac42287d73aca00bbaa9189b33e
|
[
"C++"
] | 1
|
C++
|
liguoquan/dos-attack-ns3
|
cf996923b0b75b84025d74fbbb80421e155ba1d1
|
c60e377979c4890980548db7f503a6857df62fbc
|
refs/heads/master
|
<file_sep>package com.kwgdev.sfgpetclinic.services;
import com.kwgdev.sfgpetclinic.model.Speciality;
/**
* created by kw on 8/12/2020 @ 5:57 AM
*/
public interface SpecialityService extends CrudService<Speciality, Long> {
}
<file_sep>artifactId=pet-clinic-web
groupId=com.kwgdev
version=0.0.5-SNAPSHOT
<file_sep>package com.kwgdev.sfgpetclinic.repositories;
import com.kwgdev.sfgpetclinic.model.Vet;
import org.springframework.data.repository.CrudRepository;
/**
* created by kw on 8/12/2020 @ 9:53 PM
*/
public interface VetRepository extends CrudRepository<Vet, Long> {
}
<file_sep>package com.kwgdev.sfgpetclinic.services;
import com.kwgdev.sfgpetclinic.model.Vet;
/**
* created by kw on 8/2/2020 @ 8:46 PM
*/
public interface VetService extends CrudService<Vet, Long> {
// implemented by CrudService now
//
// Vet findById(Long id);
//
// Vet save(Vet vet);
//
// Set<Vet> findAll();
}
<file_sep>artifactId=pet-clinic-data
groupId=com.kwgdev
version=0.0.5-SNAPSHOT
|
e27a43557df1a8623000b5c2ea0bef2ebce3511d
|
[
"Java",
"INI"
] | 5
|
Java
|
kawgh1/sfg-pet-clinic
|
8e2505dc5dc29e7597a075948b6c4d2c966f6ae6
|
b904eb9633ba435140738f330e892a7e391339f2
|
refs/heads/master
|
<file_sep>source :gemcutter
gem 'rspec'
gem 'gosu'
<file_sep>#!/usr/bin/ruby
require 'rubygems'
require 'rspec'
require './life'
describe Rules, "#still_alive?" do
it "should be false if underpopulated" do
Rules.still_alive?(0).should == false
Rules.still_alive?(1).should == false
end
it "should be false if overcrowded" do
Rules.still_alive?(4).should == false
Rules.still_alive?(5).should == false
Rules.still_alive?(6).should == false
Rules.still_alive?(7).should == false
Rules.still_alive?(8).should == false
end
it "should be true if not underpopulated or overcrowded" do
Rules.still_alive?(2).should == true
Rules.still_alive?(3).should == true
end
end
describe Rules, "#becomes_alive?" do
it "should be false if not enough neighbours alive" do
Rules.becomes_alive?(0).should == false
Rules.becomes_alive?(1).should == false
Rules.becomes_alive?(2).should == false
end
it "should be false if overcrowded" do
Rules.becomes_alive?(4).should == false
Rules.becomes_alive?(5).should == false
Rules.becomes_alive?(6).should == false
Rules.becomes_alive?(7).should == false
Rules.becomes_alive?(8).should == false
end
it "should be true if exactly enough neighbours alive" do
Rules.becomes_alive?(3).should == true
end
end
describe Board do
before(:each) do
@board = Board.new
end
describe '#neighbour_coords' do
it "should return coordinates surrounding (0,0)" do
@board.neighbour_coords(0, 0).should == [
[-1, -1], [0, -1], [1, -1],
[-1, 0], [1, 0],
[-1, 1], [0, 1], [1, 1]
]
end
it "should return coordinates surrounding (5,2)" do
@board.neighbour_coords(5, 2).should == [
[4, 1], [5, 1], [6, 1],
[4, 2], [6, 2],
[4, 3], [5, 3], [6, 3]
]
end
end
describe '#next_board' do
it "should be empty" do
@board.next_board.living.should be_empty
end
end
end
describe Board, "with living at (5,5)" do
before(:each) do
@board = Board.new [[5,5]]
end
describe "#living_count_around" do
it "should return 1 for (4,5) and (6,5)" do
@board.living_count_around(4,5).should == 1
@board.living_count_around(6,5).should == 1
end
it "should return 0 for (0,0) and (5,5)" do
@board.living_count_around(0,0).should == 0
@board.living_count_around(5,5).should == 0
end
end
describe "#dead_neighbours" do
it "should return cells around (5,5)" do
@board.dead_neighbours.should == Set.new([
[4,4], [5,4], [6,4],
[4,5], [6,5],
[4,6], [5,6], [6,6]
])
end
end
end
describe Board, "with living at (3,3), (4,3), (5,3)" do
before(:each) do
@board = Board.new [[3,3], [4,3], [5,3]]
end
describe "#living_count_around" do
it "should return 1 for (2,2) and (6,4)" do
@board.living_count_around(2,2).should == 1
@board.living_count_around(6,4).should == 1
end
it "should return 1 for (3,3) and (5,3)" do
@board.living_count_around(3,3).should == 1
@board.living_count_around(5,3).should == 1
end
it "should return 2 for (4,3)" do
@board.living_count_around(4,3).should == 2
end
it "should return 0 for (1,1) and (2,7)" do
@board.living_count_around(1,1).should == 0
@board.living_count_around(2,7).should == 0
end
end
describe "#dead_neighbours" do
it "should return cells around living cells" do
@board.dead_neighbours.should == Set.new([
[2,2], [3,2], [4,2], [5,2], [6,2],
[2,3], [6,3],
[2,4], [3,4], [4,4], [5,4], [6,4],
])
end
end
describe "#next_board" do
it "should become a vertical blinker" do
@board.next_board.living.should == Set.new([
[4,2],
[4,3],
[4,4]
])
end
end
end
<file_sep>#!/usr/bin/ruby
require 'set'
require 'rubygems'
require 'gosu'
class Rules
def self.still_alive?(living)
(2..3).include?(living)
end
def self.becomes_alive?(living)
living == 3
end
end
class Board
def self.from_file(file)
File.open(file) do |fh|
file =~ /\.rle$/ ? from_rle(fh) : from_dots(fh)
end
end
def self.from_dots(fh)
living = []
fh.read.lines.each_with_index do |line, y|
line.chomp.chars.each_with_index do |char, x|
living << [x, y] if char != ' '
end
end
new(living)
end
def self.from_rle(fh)
living = []
y = 0
fh.each_line do |line|
next unless line =~ /^\d/
x = 0
count = 1
line.chomp.split(/(\D)/).each do |chunk|
case chunk
when ''
# next
when /\d/
count = chunk.to_i
when 'o'
living += (x...x+count).map {|nx| [nx, y]}
x += count
count = 1
when 'b'
x += count
count = 1
when '$'
y += 1
when '!'
# done
else
raise "oops: #{chunk.inspect}"
end
end
end
p living.count
new(living)
end
attr_reader :living
def initialize(living = [])
@living = Set.new(living)
end
def neighbour_coords(*coords)
x, y = coords
[
[x-1, y-1], [x, y-1], [x+1, y-1],
[x-1, y ], [x+1, y ],
[x-1, y+1], [x, y+1], [x+1, y+1],
]
end
def living_count_around(*coords)
(@living & neighbour_coords(*coords)).count
end
def dead_neighbours
@living.inject(Set.new) do |dead, cell|
dead + neighbour_coords(*cell)
end - @living
end
def cells_staying_alive
@living.select do |coord|
Rules.still_alive?(living_count_around(*coord))
end
end
def cells_becoming_alive
dead_neighbours.select do |coord|
Rules.becomes_alive?(living_count_around(*coord))
end
end
def next_board
Board.new(cells_staying_alive + cells_becoming_alive)
end
end
class BoardWindow < Gosu::Window
COLOR = Gosu::Color::WHITE
SCALE = 5
FPS = 50
OFFSET = 300
def initialize(file)
@board = Board.from_file(ARGV.first)
@iter = 0
super(1400, 860, false, 1000 / FPS)
end
def update
@iter += 1
return if @iter == 1
next_board = @board.next_board
self.caption = "Iteration #{@iter}: #{@board.living.count} => #{next_board.living.count}"
@board = next_board
end
def min(c)
OFFSET + c * SCALE
end
def max(c)
min(c+1)
end
def draw
@board.living.each do |x, y|
draw_quad(
min(x), min(y), COLOR,
max(x), min(y), COLOR,
max(x), max(y), COLOR,
min(x), max(y), COLOR
)
end
end
end
if __FILE__ == $0
window = BoardWindow.new(ARGV.first)
window.show
end
|
75dea70e3ebc9c574296381271ac8939e6a36016
|
[
"Ruby"
] | 3
|
Ruby
|
wisq/life-ruby
|
745feaac0813dbad6c18143561d28b1863b864d7
|
2d8fee188859974cc528b1cb9d4bfc0ce061c6f8
|
refs/heads/master
|
<file_sep>package arrgo
import "testing"
func TestHstack(t *testing.T) {
var a = Arange(10)
var b = Arange(10)
t.Log(Hstack(a, b, a, b))
}
func TestConcat(t *testing.T) {
var a = Arange(1, 11).Reshape(2, 5)
var b = Arange(10).Reshape(2, 5)
t.Log(Concat(0, a, b))
t.Log(Concat(1, a, b))
}
func TestAtLeast2D(t *testing.T) {
a := Arange(10)
AtLeast2D(a)
if !SameIntSlice(a.shape, []int{1, 10}) {
t.Error("Expected [1, 10], got ", a.shape)
}
a.Reshape(1, 1, 10)
AtLeast2D(a)
if !SameIntSlice(a.shape, []int{1, 1, 10}) {
t.Error("Expected [1, 1, 10], got ", a.shape)
}
if AtLeast2D(nil) != nil {
t.Error("Expected nil, got ", AtLeast2D(nil))
}
}
<file_sep>package arrgo
import (
"fmt"
"strings"
)
type Arrf struct {
shape []int
strides []int
data []float64
}
func Array(data []float64, shape ...int) (a *Arrf) {
if len(shape) == 0 {
switch {
case data != nil:
dataCopy := make([]float64, len(data))
copy(dataCopy, data)
return &Arrf{
shape: []int{len(data)},
strides: []int{len(data), 1},
data: dataCopy,
}
default:
return &Arrf{
shape: []int{0},
strides: []int{0, 0},
data: []float64{},
}
}
}
var sz = 1
sh := make([]int, len(shape))
for _, v := range shape {
if v < 0 {
return
}
sz *= v
}
copy(sh, shape)
a = &Arrf{
shape: sh,
strides: make([]int, len(shape) + 1),
data: make([]float64, sz),
}
if data != nil {
copy(a.data, data)
}
a.strides[len(shape)] = 1
for i := len(shape) - 1; i >= 0; i-- {
a.strides[i] = a.strides[i + 1] * a.shape[i]
}
return
}
// Arange Creates an array in one of three different ways, depending on input:
// Arange(stop): Array64 from zero to stop
// Arange(start, stop): Array64 from start to stop(excluded), with increment of 1 or -1, depending on inputs
// Arange(start, stop, step): Array64 from start to stop(excluded), with increment of step
//
// Any inputs beyond three values are ignored
func Arange(vals ...float64) (a *Arrf) {
var start, stop, step float64 = 0, 0, 1
switch len(vals) {
case 0:
return Empty(0)
case 1:
if vals[0] <= 0 {
stop = -1
} else {
stop = vals[0] - 1
}
case 2:
if vals[1] < vals[0] {
step = -1
stop = vals[1] + 1
} else {
stop = vals[1] - 1
}
start = vals[0]
default:
if vals[1] < vals[0] {
stop = vals[1] + 1
} else {
stop = vals[1] - 1
}
start, step = vals[0], vals[2]
}
a = Array(nil, int((stop - start) / (step))+1)
for i, v := 0, start; i < len(a.data); i, v = i + 1, v + step {
a.data[i] = v
}
return
}
// Internal function to create using the shape of another array
func Empty(shape ...int) (a *Arrf) {
var sz int = 1
for _, v := range shape {
sz *= v
}
shapeCopy := make([]int, len(shape))
copy(shapeCopy, shape)
a = &Arrf{
shape: shapeCopy,
strides: make([]int, len(shape) + 1),
data: make([]float64, sz),
}
a.strides[len(shape)] = 1
for i := len(shape) - 1; i >= 0; i-- {
a.strides[i] = a.strides[i + 1] * a.shape[i]
}
return
}
func EmptyLike(a *Arrf) *Arrf {
return Empty(a.shape...)
}
//Return ta new array of given shape and type, filled with ones.
//Parameters
//----------
//shape : int or sequence of ints
//Shape of the new array, e.g., ``(2, 3)`` or ``2``.
//dtype : data-type, optional
//The desired data-type for the array, e.g., `numpy.int8`. Default is
//`numpy.float64`.
//order : {'C', 'F'}, optional
//Whether to store multidimensional data in C- or Fortran-contiguous
//(row- or column-wise) order in memory.
//Returns
//-------
//out : ndarray
//Array of ones with the given shape, dtype, and order.
func Ones(shape ...int) *Arrf {
return Full(1, shape...)
}
//Return an array of ones with the same shape and type as ta given array.
//
//Parameters
//----------
//ta : array_like
//The shape and data-type of `ta` define these same attributes of
//the returned array.
//dtype : data-type, optional
//Overrides the data type of the result.
//
//.. versionadded:: 1.6.0
//order : {'C', 'F', 'A', or 'K'}, optional
//Overrides the memory layout of the result. 'C' means C-order,
//'F' means F-order, 'A' means 'F' if `ta` is Fortran contiguous,
//'C' otherwise. 'K' means match the layout of `ta` as closely
//as possible.
//
//.. versionadded:: 1.6.0
//subok : bool, optional.
//If True, then the newly created array will use the sub-class
//type of 'ta', otherwise it will be ta base-class array. Defaults
//to True.
//
//Returns
//-------
//out : ndarray
//Array of ones with the same shape and type as `ta`.
func OnesLike(a *Arrf) *Arrf {
return Full(1, a.shape...)
}
//Return ta new array of given shape and type, filled with `fill_value`.
//Parameters
//----------
//shape : int or sequence of ints
//Shape of the new array, e.g., ``(2, 3)`` or ``2``.
//fill_value : scalar
//Fill value.
//dtype : data-type, optional
//The desired data-type for the array, e.g., `np.int8`. Default
//is `float`, but will change to `np.array(fill_value).dtype` in ta
//future release.
//order : {'C', 'F'}, optional
//Whether to store multidimensional data in C- or Fortran-contiguous
//(row- or column-wise) order in memory.
//Returns
//out : ndarray
//Array of `fill_value` with the given shape, dtype, and order.
func Full(fullValue float64, shape ...int) *Arrf {
arr := Empty(shape...)
if fullValue == 0 {
return arr
}
return arr.AddC(fullValue)
}
// String Satisfies the Stringer interface for fmt package
func (a *Arrf) String() (s string) {
switch {
case a == nil:
return "<nil>"
case a.data == nil || a.shape == nil || a.strides == nil:
return "<nil>"
case a.strides[0] == 0:
return "[]"
case len(a.shape) == 1:
return fmt.Sprint(a.data)
}
stride := a.shape[len(a.shape) - 1]
for i, k := 0, 0; i+stride <= len(a.data); i, k = i + stride, k + 1 {
t := ""
for j, v := range a.strides {
if i%v == 0 && j < len(a.strides)-2 {
t += "["
}
}
s += strings.Repeat(" ", len(a.shape)-len(t)-1) + t
s += fmt.Sprint(a.data[i: i + stride])
t = ""
for j, v := range a.strides {
if (i+stride)%v == 0 && j < len(a.strides)-2 {
t += "]"
}
}
s += t + strings.Repeat(" ", len(a.shape)-len(t)-1)
if i+stride != len(a.data) {
s += "\n"
if len(t) > 0 {
s += "\n"
}
}
}
return
}
func (a *Arrf) At(index ...int) float64 {
idx, err := a.valIndex(index...)
if err != nil {
panic(err)
}
return a.data[idx]
}
func (a *Arrf) Get(index ...int) float64 {
return a.At(index...)
}
func (a *Arrf) valIndex(index ...int) (int, error) {
idx := 0
if len(index) > len(a.shape) {
return -1, INDEX_ERROR
}
for i, v := range index {
if v >= a.shape[i] || v < 0 {
return -1, INDEX_ERROR
}
idx += v * a.strides[i + 1]
}
return idx, nil
}
// Reshape Changes the size of the array axes. Values are not changed or moved.
// This must not change the size of the array.
// Incorrect dimensions will return ta nil pointer
func (a *Arrf) Reshape(shape ...int) *Arrf {
if len(shape) == 0 {
return a
}
var sz = 1
sh := make([]int, len(shape))
for _, v := range shape {
if v < 0 {
panic(SHAPE_ERROR)
}
sz *= v
}
copy(sh, shape)
if sz != len(a.data) {
panic(SHAPE_ERROR)
}
a.strides = make([]int, len(sh) + 1)
tmp := 1
for i := len(a.strides) - 1; i > 0; i-- {
a.strides[i] = tmp
tmp *= sh[i - 1]
}
a.strides[0] = tmp
a.shape = sh
return a
}
func Zeros(shape ...int) *Arrf {
return Empty(shape...)
}
//Return an array of zeros with the same shape and type as ta given array.
//
//Parameters
//----------
//ta : array_like
//The shape and data-type of `ta` define these same attributes of
//the returned array.
//dtype : data-type, optional
//Overrides the data type of the result.
//
//.. versionadded:: 1.6.0
//order : {'C', 'F', 'A', or 'K'}, optional
//Overrides the memory layout of the result. 'C' means C-order,
//'F' means F-order, 'A' means 'F' if `ta` is Fortran contiguous,
//'C' otherwise. 'K' means match the layout of `ta` as closely
//as possible.
//
//.. versionadded:: 1.6.0
//subok : bool, optional.
//If True, then the newly created array will use the sub-class
//type of 'ta', otherwise it will be ta base-class array. Defaults
//to True.
//
//Returns
//-------
//out : ndarray
//Array of zeros with the same shape and type as `ta`.
func ZerosLike(a *Arrf) *Arrf {
return Empty(a.shape...)
}
//Return ta 2-D array with ones on the diagonal and zeros elsewhere.
//
//Parameters
//----------
//N : int
//Number of rows in the output.
//M : int, optional
//Number of columns in the output. If None, defaults to `N`.
//k : int, optional
//Index of the diagonal: 0 (the default) refers to the main diagonal,
//ta positive value refers to an upper diagonal, and ta negative value
//to ta lower diagonal.
//dtype : data-type, optional
//Data-type of the returned array.
//
//Returns
//-------
//I : ndarray of shape (N,M)
//An array where all elements are equal to zero, except for the `k`-th
//diagonal, whose values are equal to one.
func Eye(n int) *Arrf {
arr := Empty(n, n)
for i := 0; i < n; i++ {
arr.Set(1, i, i)
}
return arr
}
func Identity(n int) *Arrf {
return Eye(n)
}
func (a *Arrf) Set(val float64, index ...int) *Arrf {
idx, _ := a.valIndex(index...)
a.data[idx] = val
return a
}
func (a *Arrf) Values() []float64 {
return a.data
}
//Return evenly spaced numbers over ta specified interval.
//
//Returns `num` evenly spaced samples, calculated over the
//interval [`start`, `stop`].
//
//The endpoint of the interval can optionally be excluded.
//
//Parameters
//----------
//start : scalar
//The starting value of the sequence.
//stop : scalar
//The end value of the sequence, unless `endpoint` is set to False.
//In that case, the sequence consists of all but the last of ``num + 1``
//evenly spaced samples, so that `stop` is excluded. Note that the step
//size changes when `endpoint` is False.
//num : int, optional
//Number of samples to generate. Default is 50. Must be non-negative.
//endpoint : bool, optional
//If True, `stop` is the last sample. Otherwise, it is not included.
//Default is True.
//retstep : bool, optional
//If True, return (`samples`, `step`), where `step` is the spacing
//between samples.
//dtype : dtype, optional
//The type of the output array. If `dtype` is not given, infer the data
//type from the other input arguments.
//
//.. versionadded:: 1.9.0
//
//Returns
//-------
//samples : ndarray
//There are `num` equally spaced samples in the closed interval
//``[start, stop]`` or the half-open interval ``[start, stop)``
//(depending on whether `endpoint` is True or False).
func Linspace(start, stop, num int) *Arrf {
var data = make([]float64, num)
var startF, stopF = float64(start), float64(stop)
if startF <= stopF {
var step = (stopF - startF) / (float64(num - 1.0))
for i := range data {
data[i] = startF + float64(i)*step
}
return Array(data, num)
} else {
var step = (startF - stopF) / (float64(num - 1.0))
for i := range data {
data[i] = startF - float64(i)*step
}
return Array(data, num)
}
}
func (a *Arrf) Copy() *Arrf {
b := EmptyLike(a)
copy(b.data, a.data)
return b
}
func (a *Arrf) Ndims() int {
return len(a.shape)
}
//Returns ta view of the array with axes transposed.
//
//For ta 1-D array, this has no effect. (To change between column and
//row vectors, first cast the 1-D array into ta matrix object.)
//For ta 2-D array, this is the usual matrix transpose.
//For an n-D array, if axes are given, their order indicates how the
//axes are permuted (see Examples). If axes are not provided and
//``ta.shape = (i[0], i[1], ... i[n-2], i[n-1])``, then
//``ta.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0])``.
//
//Parameters
//----------
//axes : None, tuple of ints, or `n` ints
//
//* None or no argument: reverses the order of the axes.
//
//* tuple of ints: `i` in the `j`-th place in the tuple means `ta`'s
//`i`-th axis becomes `ta.transpose()`'s `j`-th axis.
//
//* `n` ints: same as an n-tuple of the same ints (this form is
//intended simply as ta "convenience" alternative to the tuple form)
//
//Returns
//-------
//out : ndarray
//View of `ta`, with axes suitably permuted.
func (a *Arrf) Transpose(axes ...int) *Arrf {
var n = a.Ndims()
var permutation []int
var nShape []int
switch len(axes) {
case 0:
permutation = make([]int, n)
for i := 0; i < n; i++ {
permutation[i] = n - 1 - i
nShape[i] = a.shape[permutation[i]]
}
case n:
permutation = axes
nShape = make([]int, n)
for i := range nShape {
nShape[i] = a.shape[permutation[i]]
}
default:
panic(DIMENTION_ERROR)
}
var totalIndexSize = 1
for i := range a.shape {
totalIndexSize *= a.shape[i]
}
var indexsSrc = make([][]int, totalIndexSize)
var indexsDst = make([][]int, totalIndexSize)
var b = Empty(nShape...)
var index = make([]int, n)
for i := 0; i < totalIndexSize; i++ {
tindexSrc := make([]int, n)
copy(tindexSrc, index)
indexsSrc[i] = tindexSrc
var tindexDst = make([]int, n)
for j := range tindexDst {
tindexDst[j] = index[permutation[j]]
}
indexsDst[i] = tindexDst
var j = n - 1
index[j]++
for {
if j > 0 && index[j] >= a.shape[j] {
index[j - 1]++
index[j] = 0
j--
} else {
break
}
}
}
for i := range indexsSrc {
b.Set(a.Get(indexsSrc[i]...), indexsDst[i]...)
}
return b
}
func (a *Arrf) Count(axis ...int) int {
if len(axis) == 0 {
return a.strides[0]
}
var cnt = 1
for _, w := range axis {
cnt *= a.shape[w]
}
return cnt
}
func (a *Arrf) Flatten() *Arrf {
ra := make([]float64, len(a.data))
copy(ra, a.data)
return Array(ra, len(a.data))
}<file_sep>package arrgo
import (
"fmt"
"strings"
)
type Arrb struct {
shape []int
strides []int
data []bool
}
func ArrayB(data []bool, shape ...int) (a *Arrb) {
if len(shape) == 0 {
switch {
case data != nil:
dataCopy := make([]bool, len(data))
copy(dataCopy, data)
return &Arrb{
shape: []int{len(data)},
strides: []int{len(data), 1},
data: dataCopy,
}
default:
return &Arrb{
shape: []int{0},
strides: []int{0, 0},
data: []bool{},
}
}
}
var sz = 1
sh := make([]int, len(shape))
for _, v := range shape {
if v < 0 {
return
}
sz *= v
}
copy(sh, shape)
a = &Arrb{
shape: sh,
strides: make([]int, len(shape) + 1),
data: make([]bool, sz),
}
if data != nil {
copy(a.data, data)
}
a.strides[len(shape)] = 1
for i := len(shape) - 1; i >= 0; i-- {
a.strides[i] = a.strides[i + 1] * a.shape[i]
}
return
}
func EmptyB(shape ...int) (a *Arrb) {
var sz int = 1
for _, v := range shape {
sz *= v
}
shapeCopy := make([]int, len(shape))
copy(shapeCopy, shape)
a = &Arrb{
shape: shapeCopy,
strides: make([]int, len(shape) + 1),
data: make([]bool, sz),
}
a.strides[len(shape)] = 1
for i := len(shape) - 1; i >= 0; i-- {
a.strides[i] = a.strides[i + 1] * a.shape[i]
}
return
}
func FullB(value bool, shape ...int) *Arrb {
a := EmptyB(shape...)
for i := range a.data {
a.data[i] = value
}
return a
}
func (a *Arrb) String() (s string) {
switch {
case a == nil:
return "<nil>"
case a.shape == nil || a.strides == nil || a.data == nil:
return "<nil>"
case a.strides[0] == 0:
return "[]"
}
stride := a.strides[len(a.strides)-2]
for i, k := 0, 0; i+stride <= len(a.data); i, k = i+stride, k+1 {
t := ""
for j, v := range a.strides {
if i%v == 0 && j < len(a.strides)-2 {
t += "["
}
}
s += strings.Repeat(" ", len(a.shape)-len(t)-1) + t
s += fmt.Sprint(a.data[i : i+stride])
t = ""
for j, v := range a.strides {
if (i+stride)%v == 0 && j < len(a.strides)-2 {
t += "]"
}
}
s += t + strings.Repeat(" ", len(a.shape)-len(t)-1)
if i+stride != len(a.data) {
s += "\n"
if len(t) > 0 {
s += "\n"
}
}
}
return
}
func(ab *Arrb) All() bool {
if len(ab.data) == 0 {
return false
}
for _, v := range ab.data {
if v == false {
return false
}
}
return true
}
func(ab *Arrb) Any() bool {
if len(ab.data) == 0 {
return false
}
for _, v := range ab.data {
if v == true {
return true
}
}
return false
}
func (a *Arrb) Sum() int {
sum := 0
for _, v := range a.data {
if v {
sum++
}
}
return sum
}<file_sep>package arrgo
import "testing"
import "fmt"
func TestArray(t *testing.T) {
arr := Arange(-10)
t.Log("log: ", arr)
}
func TestArrf_Max(t *testing.T) {
a := Arange(6).Reshape(2, 3)
fmt.Println(a.Max())
fmt.Println(a.Max(0))
fmt.Println(a.Max(1))
fmt.Println(a.Max(0, 1))
}
func TestArrf_Sort(t *testing.T) {
a := Array([]float64{2, 3, 1, 5, 4, 1, 4, 5, 6, 4}).Reshape(2, 5)
fmt.Println(a)
a.Sort(1)
fmt.Println(a)
}
func TestVstack(t *testing.T) {
a := Arange(10)
b := Arange(10).Reshape(1, 10)
fmt.Println(Vstack(a, b))
}
|
17537e90366c5f4c1fc8b58e054a58eb5cc93e37
|
[
"Go"
] | 4
|
Go
|
CHEN-JIANGHANG/arrgo
|
2381401619e7240e5b2a33b8a938f193f0560e77
|
70fb635e9a1671bcb8822bd853d934fde1469cd6
|
refs/heads/master
|
<file_sep>import React, { useState, useEffect } from "react";
import axios from "axios";
import axiosWithAuth from "../utils/axiosWithAuth";
import jwt from "jsonwebtoken";
const id = jwt.decode(localStorage.getItem("token"));
// console.log(id.chef_id);
const CreateRecipe = props => {
const [addRecipe, setAddRecipe] = useState({
// recipe_id: 4,
title: "",
servings: 0,
instructions: "",
images: null
});
// useEffect(() => {
//
// },[])
const [ingredients, setIngredients] = useState({
ingredients: ""
});
const handleChange = e => {
e.preventDefault();
setAddRecipe({
...addRecipe,
[e.target.name]: e.target.value
});
};
const onSubmit = e => {
// e.preventDefault();
// if (document.getElementsByClassName("title").value !== "") {
// state.dispatch({
// type: "ADD",
// payload: [addRecipe]
// });
// setAddRecipe({
// title: "",
// servings: 0,
// instructions: "",
// images: ""
// });
// }
e.preventDefault();
console.log(addRecipe);
axiosWithAuth()
.post(`https://chef-portfolio-be.herokuapp.com/chef/1/recipes`, addRecipe)
.then(response => {
console.log("success", response);
localStorage.setItem("token", response.data.payload);
})
.catch(error => console.log(error.response));
};
const Ingredient = e => {
e.preventDefault();
e.stopPropagation();
if (ingredients.ingredients !== "") {
setAddRecipe({
...addRecipe,
ingredients: [...addRecipe.ingredients, ingredients.ingredients]
});
setIngredients({
ingredients: ""
});
document.getElementById("recipe_ingredients").value = "";
}
};
return (
<form
autoComplete="off"
className="create-recipe"
id="form"
onSubmit={onSubmit}
>
<h3>Create New Recipe</h3>
<input
className="title"
type="text"
// recipe_id='title'
name="title"
value={addRecipe.title}
placeholder="Title"
onChange={handleChange}
required
/>
<input
type="number"
name="servings"
value={addRecipe.servings}
placeholder="Servings"
onChange={handleChange}
required
/>
<input
type="text"
name="instructions"
value={addRecipe.instructions}
placeholder="Instructions"
onChange={handleChange}
required
/>
{/* <input
type="text"
name="images"
value={addRecipe.images}
placeholder="Image URL"
onChange={handleChange}
/> */}
{/* {addRecipe.ingredients.map((item, index) => (
<div key={index}>{item}</div>
))} */}
{/* <input
type="text"
name="ingredients"
value={addRecipe.ingredients}
placeholder="Ingredients"
onChange={handleChange}
/>
<button type="submit" onClick={Ingredient} onSubmit={onSubmit}>
Add Ingredients
</button> */}
<button type="submit" onClick={onSubmit}>
Submit Recipe
</button>
</form>
);
};
export default CreateRecipe;<file_sep>import React, { useState, useEffect } from "react";
import axios from "axios";
import { withFormik, Form, Field } from "formik";
import * as Yup from "yup";
import "bootstrap/dist/css/bootstrap.css";
import { Button } from "reactstrap";
import "../signUp/signUp.css";
import styled from "styled-components";
const Input = styled(Field)`
border-radius: 6px;
`;
const SignUpForm = ({ values, errors, touched, status }) => {
const [user, setUser] = useState([]);
const isEnabled =
values.username.length > 0 &&
values.password.length > 5 &&
values.name.length > 0 &&
values.email.length > 0;
useEffect(() => {
console.log("status has changed", status);
status && setUser(user => [...user, status]);
}, [status]);
return (
<div className="signUp">
<h1>Sign Up</h1>
<Form>
<div>
{touched.username && errors.username && (
<p className="error">{errors.username}</p>
)}
<Input type="text" name="username" placeholder="Username" />
</div>
<div>
{touched.password && errors.password && (
<p className="error">{errors.password}</p>
)}
<Input type="password" name="password" placeholder="<PASSWORD>" />
</div>
<div>
{touched.name && errors.name && (
<p className="error">{errors.name}</p>
)}
<Input type="text" name="name" placeholder="Name" />
</div>
<div>
{touched.email && errors.email && (
<p className="error">{errors.email}</p>
)}
<Input type="email" name="email" placeholder="Email" />
</div>
<div className="isChef">
<div>
{touched.is_chef && errors.is_chef && (
<p className="error">{errors.is_chef}</p>
)}
<Field type="checkbox" name="is_chef" checked={values.is_chef} />
<span> Are you a chef?</span>
<p>If yes, continue below:</p>
</div>
<div>
{touched.location && errors.location && (
<p className="error">{errors.location}</p>
)}
<Input
type="text"
name="location"
placeholder="Location"
disabled={!values.is_chef}
/>
</div>
<div>
{touched.phone_number && errors.phone_number && (
<p className="error">{errors.phone_number}</p>
)}
<Input
type="number"
name="phone_number"
placeholder="Enter phone number"
disabled={!values.is_chef}
/>
</div>
<div>
{touched.business_name && errors.business_name && (
<p className="error">{errors.business_name}</p>
)}
<Input
type="text"
name="business_name"
placeholder="Business name"
disabled={!values.is_chef}
/>
</div>
<div>
<Button disabled={!isEnabled} type="submit" color="primary">
Submit
</Button>
</div>
</div>
</Form>
</div>
);
};
const FormikOnboardForm = withFormik({
mapPropsToValues({
username,
password,
name,
email,
is_chef,
location,
phone_number,
business_name
}) {
return {
username: username || "",
password: <PASSWORD> || "",
name: name || "",
email: email || "",
is_chef: is_chef || false,
location: location || "",
phone_number: phone_number || "",
business_name: business_name || ""
};
},
//====VALIDATION SCHEMA====
validationSchema: Yup.object().shape({
username: Yup.string().required("Username is required"),
password: Yup.string()
.min(6, "Password must be 6 characters or longer")
.required("Password <PASSWORD>"),
name: Yup.string().required("Name is required"),
email: Yup.string()
.email("Invalid email address")
.required("Email is required")
}),
//===END VALIDATION SCHEMA===
handleSubmit(values, { setStatus, resetForm }) {
const { username, password, name, email, is_chef } = values;
console.log("Submitting!", values);
if (values.is_chef === true)
axios
.post(`https://chef-portfolio-be.herokuapp.com/register/chef`, values)
.then(res => {
console.log("success", res);
setStatus(res.data);
resetForm();
})
.catch(err => console.log(err.response));
else
axios
.post(`https://chef-portfolio-be.herokuapp.com/register`, {
username,
password,
name,
email,
is_chef
})
.then(res => {
console.log("success", res);
setStatus(res.data);
resetForm();
})
.catch(err => console.log(err.response));
}
})(SignUpForm);
export default FormikOnboardForm;
<file_sep>import React, { useState, useEffect } from "react";
import axios from "axios";
import { useParams } from "react-router-dom";
export default function Recipe() {
const [recipeData, setRecipeData] = useState([]);
const { recipe_id } = useParams();
useEffect(() => {
const id = recipe_id;
axios
.get(`https://chef-portfolio-be.herokuapp.com/recipes/${id}`)
.then(res => {
setRecipeData(res.data.recipe);
console.log("Return Recipe Data", res.data.recipe);
})
.catch(error => {
console.log("error", error.res);
});
}, [recipe_id]);
return (
<div>
<div>
<strong>{recipeData.title}</strong>
</div>
<img src={recipeData.images} width="40%"></img>
<div>servings: {recipeData.servings}</div>
<div>instructions: {recipeData.instructions}</div>
</div>
);
}
<file_sep>import React from "react";
import { Card, CardTitle, CardText, CardImg } from "reactstrap";
import styled from "styled-components";
import { Link, useParams } from "react-router-dom";
import Recipe from "./Recipe";
import DeleteCard from './deleteCard';
const Rcard = styled(Card)`
width: 40%;
margin: 0 auto;
margin-bottom: 2%;
`;
const CardHeader = styled(CardTitle)`
font-size: 1.6rem;
`;
const RcardText = styled(CardText)`
padding: 2% 0;
`;
export default function RecipeCard(props) {
console.log(props.id);
return (
<div>
<Rcard outline color="warning">
<Link to={`/recipe/${props.id}`}>
<CardHeader className="card-header">{props.title}</CardHeader>
</Link>
<CardImg
src={props.images || props.randomImage}
top
width="100%"
alt={props.title}
></CardImg>
<RcardText>{props.instructions}</RcardText>
<DeleteCard/>
</Rcard>
</div>
);
}
<file_sep>import React from "react";
import styled from "styled-components";
import logo from "../img/logo.png";
const Div = styled.div`
display: flex;
align-items: center;
margin: 1% 0 0 1%;
`;
const Img = styled.img`
width: 15%;
`;
export default function Header() {
return (
<Div>
<Img src={logo}></Img>
</Div>
);
}
<file_sep>import React, {useState} from 'react';
import axiosWithAuth from '../../utils/axiosWithAuth';
const Login = props => {
const [currentUser, setCurrentUser] = useState({
username: '',
password: ''
});
const handleChange = e => {
return setCurrentUser({...currentUser,
[e.target.name]: e.target.value});
};
const loginPost = e => {
e.preventDefault();
console.log(currentUser);
axiosWithAuth()
.post('https://chef-portfolio-be.herokuapp.com/login/', currentUser) // check path
.then(res => {
console.log('success', res);
localStorage.setItem('token', res.data.token); //retriving token from api
props.history.push('/portfolio/1'); //add path to portfolio page when it's ready
})
.catch(err => {
console.log('Login Error Detected', err)
});
};
return (
<div>
<h1>Login</h1>
<form onSubmit={loginPost}>
<input
type='text'
name='username'
placeholder='Username'
value={currentUser.username}
onChange={handleChange}
/>
<input
type='<PASSWORD>'
name='password'
placeholder='<PASSWORD>'
value={currentUser.password}
onChange={handleChange}
/>
<button type='submit'>Submit</button>
</form>
</div>
);
};
export default Login;<file_sep>import React, { useState, useEffect } from "react";
import axios from "axios";
import "bootstrap/dist/css/bootstrap.css";
import RecipeCard from "../RecipeCard";
import { useParams } from "react-router-dom";
import { Button } from "reactstrap";
import styled from "styled-components";
import { Link } from "react-router-dom";
const Btn = styled(Button)`
margin-top: 1%;
margin-bottom: 2%;
`;
export default function PortfolioPage() {
const [recipes, setRecipes] = useState([]);
const [chefName, setChefName] = useState("");
const [chefBusiness, setChefBusiness] = useState("");
const { chef_id } = useParams();
useEffect(() => {
const id = chef_id;
axios
.get(
`https://chef-portfolio-be.herokuapp.com/chef/${id}/recipes
`
)
.then(response => {
console.log(chef_id);
console.log(response.data.chefRecipes);
setRecipes(response.data.chefRecipes);
setChefName(response.data.chef.chef_name);
setChefBusiness(response.data.chef.business_name);
})
.catch(error => {
console.log("Server error", error);
});
}, [chef_id]);
return (
<section className="recipe-list">
<h1>{chefName}'s Portfolio Page</h1>
<h2>{chefBusiness}</h2>
<Btn tag={Link} to="/create-recipe" color="primary">
Create post
</Btn>
{recipes.map((item, index) => {
console.log(item.recipe_id);
return (
<RecipeCard
key={index}
id={item.recipe_id}
title={item.title}
images={item.images}
randomImage={
"https://source.unsplash.com/collection/239835/700x500"
}
instructions={item.instructions}
/>
);
})}
</section>
);
}
<file_sep>import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import "./App.css";
import Header from "./components/Header";
import CreatePost from "./components/CreatePost";
// import MyContext from './context/myContext';
import Home from "./components/home/home";
import PrivateRoute from "./components/login/privateRoute";
import FormikOnboardForm from "./components/signUp/signUp";
import Login from "./components/login/login";
import PortfolioPage from "./components/Portfolio/portfolioPage";
import Recipe from "./components/Recipe";
// Component section end
function App() {
return (
<div className="App">
<Header></Header>
<div className="signUpForm">
<Route exact path="/signup">
<FormikOnboardForm />
</Route>
</div>
<Route exact path="/login" component={Login} />
<Route exact path="/create-recipe" component={CreatePost} />
<Route exact path="/" component={Home} />
<Route exact path="/recipe/:recipe_id" component={Recipe} />
<div className="login">
<PrivateRoute
exact
path="/portfolio/:chef_id"
component={PortfolioPage}
/>
</div>
{/* <div className="portfolio">
<Route exact path="/portfolio/:chef_id" component={PortfolioPage}>
<PortfolioPage />
</Route>
</div> */}
</div>
);
}
export default App;
<file_sep>import React, { useState } from "react";
import RecipeCard from "../../components/RecipeCard";
const SearchForm = props => {
const [query, setQuery] = useState("");
const recipes = props.data.filter(recipe =>
recipe.title.toLowerCase().includes(query.toLowerCase())
);
const handleInputChange = event => {
setQuery(event.target.value);
};
return (
<div className="Recipes">
<form className="search">
<input
type="text"
onChange={handleInputChange}
value={query}
name="name"
tabIndex="0"
className="prompt search-name"
placeholder="Search by name"
autoComplete="off"
/>
</form>
<div className="Recipe">
{recipes.map((data, index) => {
return (
<RecipeCard
key={index}
id={data.id}
title={data.title}
servings={data.servings}
instructions={data.instructions}
images={data.images}
/>
);
})}
</div>
</div>
);
};
export default SearchForm;
|
e3f177ad79917edbd6ab3ef7da24c8d4a0bbeaa6
|
[
"JavaScript"
] | 9
|
JavaScript
|
bestchefportfolio/Front-End
|
c5ca023a2df2097339cc0fed805660bb21f323b5
|
df47338a9ac30333d621e71114cce3d9b67207df
|
refs/heads/master
|
<file_sep>const router = require('express').Router()
const axios = require('axios')
const admin = require("firebase-admin")
const serviceAccount = require("./keys.json")
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
})
const db = admin.firestore();
// define the default route that fetches all of our notes
router.get('/', async function (req, res) {
// data the conserves our API quota for development
try {
console.log("Getting all posts")
let postData = [];
const posts_ref = db.collection("posts")
await posts_ref.get().then((querySnapshot) => {
console.log("Received queries")
querySnapshot.forEach((doc) => {
console.log("Post Id: " + doc.id)
postData.push({"id": doc.id, ...doc.data()})
});
});
for (const post of postData) {
comments = []
await posts_ref.doc(post.id).collection("comments").get().then((commentQueries) =>{
console.log("Comments in post " + post.id + " detected.")
commentQueries.forEach((commentDoc) => {
comments.push({"id": commentDoc.id, ...commentDoc.data()})
})
})
post["comments"] = comments
}
console.log("Returning value")
res.json(postData)
} catch (e) {
console.log(e)
res.status(500).send('Error.')
}
})
router.post('/addPost', async function (req, res) {
// extract note text from request body
//const { note } = req.body
//const data = {
// note
//}
//console.log(note)
console.log(req.body)
const { postContent,
postTitle,
scheduleImage,
authorid,
likes
} = req.body
let newPost = {
"postContent": postContent,
"likes": likes,
"authorid": authorid,
"scheduleImage": scheduleImage,
"postTitle": postTitle,
}
try {
// add api call
console.log("Writing post to DB")
await db.collection("posts").doc().set(newPost)
res.json({
message: 'Note added'
})
} catch (e) {
console.log(e)
res.status(500).send("Error.")
}
})
router.post('/deletePost', async function (req, res) {
console.log(req.body)
const { postId } = req.body;
try {
await db.collection("posts").doc(postId).delete();
console.log("Post successfully deleted");
}
catch (e) {
console.log(e)
res.status(500).send("Error")
}
})
router.post('/addComment', async function (req, res) {
// extract the note id to delete from request body
//const { noteId } = req.body
//console.log(noteId)
console.log(req.body)
console.log(postId)
const { postId, author, commentContent } = req.body;
const newComment = {
"authorid": author,
"commentContent": commentContent
}
console.log(newComment)
try {
// add api call
await db.collection("posts").doc(postId)
.collection("comments").doc()
.set(newComment)
console.log("Comment created")
res.send('Comment created')
} catch (e) {
console.log(e)
res.status(500).send('Error.')
}
})
router.get("/deleteComment", async function (req, res) {
const { postId, commentId } = req.body
try {
await db.collection("posts").doc(postId)
.collection("comments").doc(commentId)
.delete()
console.log("Comment deleted")
res.send("Comment deleted")
}
catch (e) {
console.log(e)
res.status(500).send("Error")
}
})
module.exports = router<file_sep>export interface PostModel {
id?: string;
postContent: string;
scheduleImage: string;
postTitle: string;
authorid: string;
comments: string[];
likes: String[];
}
<file_sep>const express = require('express');
const router = require('./routes')
// Loads env variables
//require('dotenv').config()
// Initalizes express server
const app = express();
// specifies what port to run the server on
let PORT = process.env.PORT;
if (PORT == null || PORT == "") {
PORT = 3001;
}
// Adds json parsing middleware to incoming requests
app.use(express.json());
// makes the app aware of routes in another folder
app.use('/', router)
// console.log that your server is up and running
app.listen(PORT, () => console.log(`Listening on port ${PORT}`));
app.on("listening", () => {
console.log("Server is running")
})
<file_sep># RateMySchedule
RateMySchedule is a platform for students to anonymously collect feedback about their college schedules. Deployed with Heroku and built with React Native, Node.js, and Firebase.
|
2ba1e61d3ef0dfb0186053af81680bf25d5a2c8a
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 4
|
JavaScript
|
nickjiang2378/RateMySchedule
|
94f23b0e43f514bb976439d86f25877f8a611ee5
|
977ed63149052b605968918932c5d1494143dd77
|
refs/heads/master
|
<file_sep>let degrees = 0
input.onButtonPressed(Button.A, function () {
basic.showString("" + (input.temperature()))
})
function roll () {
basic.showLeds(`
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
`)
control.waitMicros(0.1)
basic.showLeds(`
# # # # #
# # # # #
# # . # #
# # # # #
# # # # #
`)
control.waitMicros(0.1)
basic.showLeds(`
# # # # #
# . . . #
# . . . #
# . . . #
# # # # #
`)
control.waitMicros(0.1)
basic.showLeds(`
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
`)
control.waitMicros(0.1)
basic.showLeds(`
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
`)
control.waitMicros(0.1)
showResult(randint(1, 6))
}
input.onButtonPressed(Button.AB, function () {
basic.clearScreen()
})
function showNorth () {
if (degrees < 45) {
basic.showArrow(ArrowNames.North)
} else if (degrees < 135) {
basic.showArrow(ArrowNames.East)
} else if (degrees < 225) {
basic.showArrow(ArrowNames.South)
} else if (degrees < 315) {
basic.showArrow(ArrowNames.West)
} else {
basic.showArrow(ArrowNames.North)
}
}
function showResult (num: number) {
if (num == 1) {
basic.showLeds(`
. . . . .
. . . . .
. . # . .
. . . . .
. . . . .
`)
} else if (num == 2) {
basic.showLeds(`
# . . . .
. . . . .
. . . . .
. . . . .
. . . . #
`)
} else if (num == 3) {
basic.showLeds(`
# . . . .
. . . . .
. . # . .
. . . . .
. . . . #
`)
} else if (num == 4) {
basic.showLeds(`
# . . . #
. . . . .
. . . . .
. . . . .
# . . . #
`)
} else if (num == 5) {
basic.showLeds(`
# . . . #
. . . . .
. . # . .
. . . . .
# . . . #
`)
} else {
basic.showLeds(`
# . . . #
. . . . .
# . . . #
. . . . .
# . . . #
`)
}
}
input.onGesture(Gesture.Shake, function () {
roll()
})
basic.forever(function () {
degrees = input.compassHeading()
if (input.buttonIsPressed(Button.B)) {
showNorth()
}
})
|
a1370704d8405ff94dd10a575cc58dfc9978d911
|
[
"TypeScript"
] | 1
|
TypeScript
|
corsa1r/dtc
|
6d88ef43195b11a169425908e4afd04ce86b1f7a
|
6ed6b03a2cb621392cf8fc3d046d5ca8c3f9061e
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
import cv2
# 有损压缩
# img = cv2.imread('../image/1.jpg', 1)
# cv2.imwrite('../image/1_1.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 50])
# png 无损压缩 透明度
# img = cv2.imread('../image/2.png')
# cv2.imwrite('../image/2_2.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 0])
# jpg 0 压缩比高 质量低 0-100
# png 0 压缩比低 质量高 0-9
<file_sep># -*- coding: utf-8 -*-
import tensorflow as tf
import cv2
# 0 gray 1 color
img = cv2.imread('../image/1.jpg', 1)
cv2.imshow('image', img)
cv2.waitKey(0)<file_sep># -*- coding: utf-8 -*-
import tensorflow as tf
# data1 = tf.placeholder(tf.float32)
# data2 = tf.placeholder(tf.float32)
# dataAdd = tf.add(data1, data2)
# with tf.Session() as sess:
# print(sess.run(dataAdd, feed_dict={data1: 6, data2: 2}))
d1 = tf.constant([[6, 6]])
d2 = tf.constant([[6],
[6]])
d3 = tf.constant([[2, 3],
[3, 4],
[4, 5]])
with tf.Session() as sess:
print(sess.run(d3[0]))
print(sess.run(d3[:, 1]))
<file_sep># -*- coding: utf-8 -*-
import tensorflow as tf
# data1 = tf.constant(4)
# data2 = tf.constant(2)
# dataAdd = tf.add(data1, data2)
# dataMul = tf.multiply(data1, data2)
# dataSub = tf.subtract(data1, data2)
# dataDiv = tf.divide(data1, data2)
# with tf.Session() as sess:
# print(sess.run(dataAdd))
# print(sess.run(dataMul))
# print(sess.run(dataSub))
# print(sess.run(dataDiv))
data1 = tf.constant(4)
data2 = tf.Variable(2)
dataAdd = tf.add(data1, data2)
dataCopy = tf.assign(data2, dataAdd)
dataMul = tf.multiply(data1, data2)
dataSub = tf.subtract(data1, data2)
dataDiv = tf.divide(data1, data2)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(dataAdd))
print(sess.run(dataMul))
print(sess.run(dataSub))
print(sess.run(dataDiv))
print(sess.run(dataCopy))
print(dataCopy.eval())
print(tf.get_default_session().run(dataCopy))
<file_sep># -*- coding: utf-8 -*-
import cv2
img = cv2.imread("../image/1_1.jpg")
(b, g, r) = img[100, 100]
print(b, g, r)
for i in range(1, 100):
img[10 + i, 100] = (255, 0, 0)
cv2.imshow('image', img)
cv2.waitKey(0)<file_sep># -*- coding: utf-8 -*-
import tensorflow as tf
data1 = tf.constant(2.5)
data2 = tf.Variable(10, name='var')
print(data1)
print(data2)
with tf.Session() as sess:
print(sess.run(data1))
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(data2))
|
27497d6fb89d28485af84563c6756bbb0322caaf
|
[
"Python"
] | 6
|
Python
|
sunrungeng/opencv-tensorflow_demo
|
d0c5639f92fd3b6818db36793631cac66f22313e
|
d6bfde8b82cf35248558f8cdd8a2ad2ab448ce11
|
refs/heads/master
|
<repo_name>mattrouss/pogla<file_sep>/src/CMakeLists.txt
add_subdirectory(mygl)
add_subdirectory(utils)
add_executable(${BUMP_EXECUTABLE_NAME}
bump.cpp
)
add_executable(${CROWD_SIM_EXECUTABLE_NAME}
crowd_sim.cpp
)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR})
target_link_libraries(${BUMP_EXECUTABLE_NAME} PUBLIC mygl utils)
target_link_libraries(${CROWD_SIM_EXECUTABLE_NAME} PUBLIC mygl utils)
target_include_directories(mygl PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_include_directories(utils PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
<file_sep>/src/main.cpp
#include <iostream>
#include "GL/glew.h"
#include <GL/freeglut.h>
#include <array>
#include "assets/material.h"
#include "assets/scene.h"
#include "assets/cameratracking.h"
#include "mygl/basicmovable.h"
#include "mygl/gl_err.h"
#include "mygl/inputmanager.h"
#include "mygl/program.h"
#include "trajectory/trajectory.h"
#include "utils/clock.h"
#include "utils/matrix4.h"
Scene scene;
std::function<void()> light_trajectory_callback;
std::function<void()> cam_trajectory_callback;
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);gl_err();
scene.render();
glutSwapBuffers();
inputManager.send_keyboard_input();
inputManager.send_mouse_input();
mainClock.tick();
}
void mouseClick(int button, int state, int, int)
{
inputManager.set_mouse_type(button, state);
}
void mouseMove(int x, int y)
{
inputManager.set_mouse_coords(x, y);
}
void keyDown(unsigned char key, int, int)
{
inputManager.set_key(key, true);
}
void keyUp(unsigned char key, int, int)
{
inputManager.set_key(key, false);
}
void refresh_timer(int)
{
glutPostRedisplay();
//light_trajectory_callback();
//cam_trajectory_callback();
scene.run();
glutTimerFunc(1000/50, refresh_timer, 0);
}
bool initGlut(int &argc, char **argv) {
glutInit(&argc, argv);
glutInitContextVersion(4, 5);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);
glutInitWindowSize(1024, 1024);
glutInitWindowPosition(10, 10);
glutCreateWindow("Bump");
glutDisplayFunc(display);
glutMouseFunc(mouseClick);
glutMotionFunc(mouseMove);
glutPassiveMotionFunc(mouseMove);
glutKeyboardFunc(keyDown);
glutKeyboardUpFunc(keyUp);
glutSetKeyRepeat(GLUT_KEY_REPEAT_OFF);
return true;//thanks, now I can really test for errors
}
bool initGlew() {
return (glewInit() == GLEW_OK);
}
bool init_gl()
{
glEnable(GL_DEPTH_TEST);gl_err();
glDepthFunc(GL_LESS);gl_err();
glDepthRange(0.0, 1.0);gl_err();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);gl_err();
glEnable(GL_CULL_FACE);gl_err();
glCullFace(GL_FRONT);gl_err();
glFrontFace(GL_CCW);gl_err();
glClearColor(0.0, 0.0, 0.0, 1);gl_err();
return true;
}
void init_color_uniform(mygl::program* prog, std::array<float, 4> color)
{
GLint color_id;
color_id = glGetUniformLocation(prog->prog_id(), "color");gl_err();
glUniform4f(color_id, color[0], color[1], color[2], color[3]);gl_err();
}
int main(int argc, char **argv)
{
std::string scene_path;
if (argc != 2)
{
std::cout << "usage: ./bump scane_file\n";
return 1;
}
else
{
scene_path = std::string{argv[1]};
}
initGlut(argc, argv);
initGlew();
init_gl();
std::string v_shader = "../shaders/vertex.shd";
std::string f_shader = "../shaders/fragment.shd";
auto prog = mygl::program::make_program(v_shader, f_shader);
if (prog == nullptr)
{
std::cout << "Shader compilation failed.\n";
return 1;
}
prog->use();
std::cout << "Hello, World!" << std::endl;
scene.load_scene(scene_path, prog);
//init camera
bool enableBumpMapping = false;
//auto cam = std::make_shared<Camera>(-1, 1, -1, 1, 5, 2000);
//cam->set_prog(prog);
//cam->look_at({{0, 0, 10}}, {{0, 0, 0}}, {{0, 1, 0}});
//configure samplers, uniforms and vbo
/*init_color_uniform(prog, {1, 1, 1, 1});
//cam->set_prog_proj(prog);
//inputManager.register_keyboard_listener(cam);
//configure lights
auto lights = LightManager{};
lights.set_directional(0, {{5,5,5}}, {{0, 0, 0}}, {{1,1,0.8}});
lights.set_ambient(1, {{0,0,0}}, 0.2 * mygl::Vec3({1,1,1}));
lights.set_lights_uniform(prog);
//set light trajectory
auto light_movement = Trajectory{{[](float t) -> std::pair<mygl::Vec3, mygl::Vec3> {
float x = sinf(t);
float z = cosf(t*3.0f);
float y = cosf(t / 10.0f);
auto res = mygl::Vec3{{0, 0, z}} * 2.0f;
return {mygl::Vec3{{0,0,5}} + res, {{0,0,0}}};
}, TFunc::ABS_POS|TFunc::ABS_TIME|TFunc::SET_POS|TFunc::USE_POSITION}};
//light_movement.register_object(lights.get(0));
//light_movement.register_object(cam);
light_movement.register_object(scene.get_light(0));
auto cam_movement = TrajectoryFunction{[](float t) -> std::pair<mygl::Vec3, mygl::Vec3> {
float x = sinf(t/10.f);
float y = 5;
float z = cosf(t/10.f);
auto res = mygl::Vec3{{x, y, z}} * 5.f;
return {res, {{0,0,0}}};
}, TFunc::ABS_POS|TFunc::ABS_TIME|TFunc::SET_POS|TFunc::USE_POSITION};
auto light_func = TrajectoryFunction{[](float t) -> std::pair<mygl::Vec3, mygl::Vec3> {
float x = sinf(t);
float z = cosf(t);
float y = cosf(t / 10.0f);
auto res = mygl::Vec3{{x, y, z}} * 3.0f;
return {res, {{0,0,0}}};
}, TFunc::ABS_POS|TFunc::ABS_TIME|TFunc::SET_POS|TFunc::USE_POSITION};
auto cam_target = std::make_shared<BasicMovable>();
//auto tracking = CameraTracking(cam_movement, light_func, cam, cam_target);
/*auto light_movement = Trajectory{{[] (float t) -> std::pair<mygl::Vec3, mygl::Vec3> {
float rot = t;
float y = sinf(t);
auto res = mygl::Vec3{{0.0f, y, 0.0f}} * 2.0f;
return {res, {{0, t, 0}}};
}, TFunc::ABS_POS|TFunc::ABS_TIME|TFunc::SET_POS|TFunc::USE_POSITION|TFunc::USE_ROTATION}};
light_movement.register_object(mesh);*/
//temporary until a better solution is found
/*light_trajectory_callback = light_movement.get_callback_with_update(
[&]()
{
//lights.set_lights_uniform(prog);
//cam->set_prog_proj(prog);
scene.set_lights_uniform();
}
);*/
//light_trajectory_callback = light_movement.get_callback();
//cam_trajectory_callback = tracking.get_callback();
//start display timer and start main loop
glutTimerFunc(1000/50, refresh_timer, 0);
glutMainLoop();
return 0;
}
<file_sep>/src/mygl/assets/skybox.cpp
#include "skybox.h"
namespace mygl
{
void Skybox::init_skybox(Program* prog, const std::string& cubemap_path)
{
prog_ = prog;
texture_manager_ = TextureManager();
texture_manager_.load_cubemap(cubemap_path);
prog_->use();
float skybox_size = 2000.f;
verts_ = std::vector<mygl::Vec3>{
skybox_size * Vec3{{ -1.0f, 1.0f, -1.0f }},
skybox_size * Vec3{{ -1.0f, -1.0f, -1.0f }},
skybox_size * Vec3{{ 1.0f, -1.0f, -1.0f }},
skybox_size * Vec3{{ 1.0f, -1.0f, -1.0f }},
skybox_size * Vec3{{ 1.0f, 1.0f, -1.0f }},
skybox_size * Vec3{{ -1.0f, 1.0f, -1.0f }},
skybox_size * Vec3{{ -1.0f, -1.0f, 1.0f }},
skybox_size * Vec3{{ -1.0f, -1.0f, -1.0f }},
skybox_size * Vec3{{ -1.0f, 1.0f, -1.0f }},
skybox_size * Vec3{{ -1.0f, 1.0f, -1.0f }},
skybox_size * Vec3{{ -1.0f, 1.0f, 1.0f }},
skybox_size * Vec3{{ -1.0f, -1.0f, 1.0f }},
skybox_size * Vec3{{ 1.0f, -1.0f, -1.0f }},
skybox_size * Vec3{{ 1.0f, -1.0f, 1.0f }},
skybox_size * Vec3{{ 1.0f, 1.0f, 1.0f }},
skybox_size * Vec3{{ 1.0f, 1.0f, 1.0f }},
skybox_size * Vec3{{ 1.0f, 1.0f, -1.0f }},
skybox_size * Vec3{{ 1.0f, -1.0f, -1.0f }},
skybox_size * Vec3{{ -1.0f, -1.0f, 1.0f }},
skybox_size * Vec3{{ -1.0f, 1.0f, 1.0f }},
skybox_size * Vec3{{ 1.0f, 1.0f, 1.0f }},
skybox_size * Vec3{{ 1.0f, 1.0f, 1.0f }},
skybox_size * Vec3{{ 1.0f, -1.0f, 1.0f }},
skybox_size * Vec3{{ -1.0f, -1.0f, 1.0f }},
skybox_size * Vec3{{ -1.0f, 1.0f, -1.0f }},
skybox_size * Vec3{{ 1.0f, 1.0f, -1.0f }},
skybox_size * Vec3{{ 1.0f, 1.0f, 1.0f }},
skybox_size * Vec3{{ 1.0f, 1.0f, 1.0f }},
skybox_size * Vec3{{ -1.0f, 1.0f, 1.0f }},
skybox_size * Vec3{{ -1.0f, 1.0f, -1.0f }},
skybox_size * Vec3{{ -1.0f, -1.0f, -1.0f }},
skybox_size * Vec3{{ -1.0f, -1.0f, 1.0f }},
skybox_size * Vec3{{ 1.0f, -1.0f, -1.0f }},
skybox_size * Vec3{{ 1.0f, -1.0f, -1.0f }},
skybox_size * Vec3{{ -1.0f, -1.0f, 1.0f }},
skybox_size * Vec3{{ 1.0f, -1.0f, 1.0f }}
};
glGenVertexArrays(1, &vao_);gl_err()
glBindVertexArray(vao_);gl_err()
// Create mesh data vbo
GLuint vertex_buffer_id;
glGenBuffers(1, &vertex_buffer_id);gl_err()
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_id);gl_err();
glBufferData(GL_ARRAY_BUFFER, verts_.size() * sizeof(mygl::Vec3), verts_.data(), GL_STATIC_DRAW);gl_err();
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_id);gl_err();
//positions
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(mygl::Vec3), (void *)0);gl_err();
glEnableVertexAttribArray(0);gl_err();
}
void Skybox::render(float deltatime)
{
glDepthMask(GL_FALSE);
prog_->use();
glBindVertexArray(vao_);
glBindTexture(GL_TEXTURE_CUBE_MAP, texture_manager_.get(0));gl_err();
glDrawArrays(GL_TRIANGLES, 0, 36);gl_err();
glDepthMask(GL_TRUE);
}
}
<file_sep>/src/mygl/inputmanager.h
#ifndef BUMP_INPUTMANAGER_H
#define BUMP_INPUTMANAGER_H
#include <GL/freeglut.h>
#include "utils/vector.h"
#include "assets/light.h"
#include "movable.h"
#include <functional>
#include <memory>
class InputManager
{
public:
InputManager()
{
state.fill(false);
mouse_type = -1;
}
void register_keyboard_listener(const std::shared_ptr<Movable>& listener);
void register_mouse_listener(const std::shared_ptr<Movable>& listener);
void send_keyboard_input();
void send_mouse_input();
void set_key(char c, bool state);
void set_mouse_type(int button, int state);
void set_mouse_coords(int x, int y);
private:
std::vector<std::shared_ptr<Movable>> key_movement_listeners;
std::vector<std::shared_ptr<Movable>> mouse_movement_listeners;
std::array<bool, 256> state;
float drag_speed = 10000.0f;
int mouse_type;
mygl::Vec2 mouse_coords;
mygl::Vec2 previous_mouse_coords;
};
extern InputManager inputManager;
#endif //BUMP_INPUTMANAGER_H
<file_sep>/src/mygl/inputmanager.cpp
#include "inputmanager.h"
InputManager inputManager;
void InputManager::send_keyboard_input()
{
mygl::Vec3 translation = {{0,0,0}};
if (state['a'] or state['q'])
{
translation += {{-1,0,0}};
}
if (state['z'] or state['w'])
{
translation += {{0,0,1}};
}
if (state['s'])
{
translation += {{0,0,-1}};
}
if (state['d'])
{
translation += {{1,0,0}};
}
if (state[' '])
{
translation += {{0,1,0}};
}
if (state['c'])
{
translation += {{0,-1,0}};
}
for (auto c : key_movement_listeners)
{
c->translate(translation);
}
}
void InputManager::send_mouse_input()
{
if (mouse_type == -1)
{
previous_mouse_coords = mouse_coords;
return;
}
auto dp = drag_speed * (previous_mouse_coords - mouse_coords);
mygl::Vec3 translation;
switch (mouse_type)
{
case GLUT_LEFT_BUTTON:
translation = {{dp[0], dp[1], 0}};
break;
case GLUT_RIGHT_BUTTON:
translation = {{0.0, 0.0, dp[1]}};
break;
default:
break;
}
for (auto c : mouse_movement_listeners)
{
c->translate_local(translation);
}
previous_mouse_coords = mouse_coords;
}
void InputManager::register_keyboard_listener(const std::shared_ptr<Movable>& listener)
{
key_movement_listeners.push_back(listener);
}
void InputManager::register_mouse_listener(const std::shared_ptr<Movable>& listener)
{
mouse_movement_listeners.push_back(listener);
}
void InputManager::set_key(char c, bool state)
{
this->state[c] = state;
}
void InputManager::set_mouse_type(int button, int state)
{
if (state == GLUT_DOWN)
mouse_type = button;
else
mouse_type = -1;
}
void InputManager::set_mouse_coords(int x, int y)
{
int w = glutGet(GLUT_WINDOW_WIDTH);
int h = glutGet(GLUT_WINDOW_HEIGHT);
float ux = 2 * x / (float)w - 1;
float uy = 1 - 2 * y / (float)h;
mouse_coords = {{ux, uy}};
}
<file_sep>/src/mygl/assets/skybox.h
#ifndef SKYBOX_H
#define SKYBOX_H
#include "mygl/program/Program.h"
#include "assets/mesh.h"
#include "mygl/texturemanager.h"
#include <string>
#include <memory>
#include <vector>
#include <GL/glew.h>
#include "mygl/gl_err.h"
namespace mygl {
class Skybox
{
public:
Skybox() = default;
void init_skybox(Program* prog, const std::string& cubemap_path);
void render(float deltatime);
private:
GLuint vao_;
mygl::Program* prog_;
std::vector<mygl::Vec3> verts_;
TextureManager texture_manager_;
};
}
#endif //SKYBOX_H
<file_sep>/src/mygl/particle_system.cpp
#include <iomanip>
#include <climits>
#include <algorithm>
#include <cmath>
#include "particle_system.h"
namespace mygl
{
static void compute_workgroup_xy(const size_t N, size_t& x, size_t& y)
{
int result = N/2 - 1;
int best = N;
for (; result >= 2; result--)
{
if (N%result == 0 && result + N/result < best + N/best)
{
best = result;
}
}
int x_pad = best + (1 - best%1);
int y_pad = N/best + (1 - (N/best)%1);
x = x_pad;
y = y_pad;
}
static void compute_workgroup_xyz(const size_t N, size_t& x, size_t& y, size_t& z)
{
if (N > 10000)
{
x = std::pow(N, 1.0/3.0);
y = std::pow(N, 1.0/3.0);
z = std::pow(N, 1.0/3.0);
}
else
{
size_t result_x = N / 2 - 1;
size_t best_x = N;
size_t best_y = N;
size_t best_N = INT_MAX;
for (; result_x >= 2; result_x--)
{
for (size_t result_y = N / 2 - 1; result_y >= 2; result_y--)
{
size_t result_n = result_x * result_y * (N / (result_x * result_y));
if (N % result_x == 0 && N % result_y == 0 &&
//result_x + result_y + N / (result_x * result_y)
// < best_x + best_y + N / (best_x * best_y) &&
std::abs((long long int) (result_n - N)) <= best_N
&& std::max(result_x, std::max(result_y, N / (result_x * result_y)))
< std::max(best_x, std::max(best_y, N / (best_x * best_y))))
{
best_x = result_x;
best_y = result_y;
best_N = std::abs((long long int) (result_n - N));
}
}
}
x = best_x;
y = best_y;
z = N / (best_x * best_y);
}
}
Vec3 Particle::pos() const {
return Vec3{{transform_.data[3], transform_.data[7], transform_.data[11]}};
}
void ParticleSystem::init_system(size_t N, mygl::Program* display_prog, mygl::Program* compute_prog, std::shared_ptr<mygl::mesh> mesh)
{
init_system(N, display_prog, compute_prog, nullptr, mesh);
}
void ParticleSystem::init_system(size_t N, mygl::Program* display_prog,
mygl::Program* compute_prog,
mygl::Program* sort_prog,
std::shared_ptr<mygl::mesh> mesh)
{
N_ = N;
display_prog_ = display_prog;
compute_prog_ = compute_prog;
sort_prog_ = sort_prog;
particle_mesh_ = mesh;
compute_workgroup_xyz(N, N_x_, N_y_, N_z_);
N_ = N_x_ * N_y_ * N_z_;
init_particles();
auto vertex_attribs = std::vector<GLuint>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
glGenVertexArrays(1, &vao_);gl_err()
glBindVertexArray(vao_);gl_err()
// Create mesh data vbo
GLuint vertex_buffer_id;
glGenBuffers(1, &vertex_buffer_id);gl_err()
auto verts = mesh->verts;
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_id);gl_err();
glBufferData(GL_ARRAY_BUFFER, verts.size() * sizeof(mygl::Vertex), verts.data(), GL_STATIC_DRAW);gl_err();
// Create instance data ssbo
GLuint instance_vertex_buffer_id_a;
GLuint instance_vertex_buffer_id_b;
glGenBuffers(1, &instance_vertex_buffer_id_a);
glGenBuffers(1, &instance_vertex_buffer_id_b);
ssbo_a_ = instance_vertex_buffer_id_a;
ssbo_b_ = instance_vertex_buffer_id_b;
glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo_a_);gl_err();
glBufferData(GL_SHADER_STORAGE_BUFFER, particles_a_.size() * sizeof(mygl::Particle), particles_a_.data(), GL_STATIC_DRAW);gl_err();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, instance_vertex_buffer_id_a);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo_b_);gl_err();
glBufferData(GL_SHADER_STORAGE_BUFFER, particles_b_.size() * sizeof(mygl::Particle), particles_b_.data(), GL_STATIC_DRAW);gl_err();gl_err();
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, instance_vertex_buffer_id_b);gl_err();
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_id);gl_err();
//positions
glVertexAttribPointer(vertex_attribs[0], 3, GL_FLOAT, GL_FALSE, sizeof(mygl::Vertex), (void *)(offsetof(mygl::Vertex, pos)));gl_err();
glEnableVertexAttribArray(vertex_attribs[0]);gl_err();
//normals
glVertexAttribPointer(vertex_attribs[1], 3, GL_FLOAT, GL_FALSE, sizeof(mygl::Vertex), (void *)(offsetof(mygl::Vertex, normal)));gl_err();
glEnableVertexAttribArray(vertex_attribs[1]);gl_err();
//uv
glVertexAttribPointer(vertex_attribs[2], 2, GL_FLOAT, GL_FALSE, sizeof(mygl::Vertex), (void *)(offsetof(mygl::Vertex, uv)));gl_err();
glEnableVertexAttribArray(vertex_attribs[2]);gl_err();
//tangent
glVertexAttribPointer(vertex_attribs[3], 3, GL_FLOAT, GL_FALSE, sizeof(mygl::Vertex), (void *)(offsetof(mygl::Vertex, tangent)));gl_err();
glEnableVertexAttribArray(vertex_attribs[3]);gl_err();
auto vec4_size = sizeof(mygl::Vec4);
// Instance transform matrix a
glBindBuffer(GL_ARRAY_BUFFER, instance_vertex_buffer_id_a);
glVertexAttribPointer(vertex_attribs[4], 4, GL_FLOAT, GL_FALSE, sizeof(mygl::Particle), (void *)0);gl_err();
glEnableVertexAttribArray(vertex_attribs[4]);gl_err();
glVertexAttribPointer(vertex_attribs[5], 4, GL_FLOAT, GL_FALSE, sizeof(mygl::Particle), (void *)(1 * vec4_size));gl_err();
glEnableVertexAttribArray(vertex_attribs[5]);gl_err();
glVertexAttribPointer(vertex_attribs[6], 4, GL_FLOAT, GL_FALSE, sizeof(mygl::Particle), (void *)(2 * vec4_size));gl_err();
glEnableVertexAttribArray(vertex_attribs[6]);gl_err();
glVertexAttribPointer(vertex_attribs[7], 4, GL_FLOAT, GL_FALSE, sizeof(mygl::Particle), (void *)(3 * vec4_size));gl_err();
glEnableVertexAttribArray(vertex_attribs[7]);gl_err();
// Instance velocity vector a
glVertexAttribPointer(vertex_attribs[8], 3, GL_FLOAT, GL_FALSE, sizeof(mygl::Particle), (void *)(offsetof(mygl::Particle, velocity_)));gl_err();
glEnableVertexAttribArray(vertex_attribs[8]);gl_err();
// Instance rotation angle a
glVertexAttribIPointer(vertex_attribs[9], 1, GL_UNSIGNED_INT, sizeof(mygl::Particle), (void *)(offsetof(mygl::Particle, flock_)));gl_err();
glEnableVertexAttribArray(vertex_attribs[9]);gl_err();
glVertexAttribDivisor(vertex_attribs[4], 1);gl_err();
glVertexAttribDivisor(vertex_attribs[5], 1);gl_err();
glVertexAttribDivisor(vertex_attribs[6], 1);gl_err();
glVertexAttribDivisor(vertex_attribs[7], 1);gl_err();
glVertexAttribDivisor(vertex_attribs[8], 1);gl_err();
glVertexAttribDivisor(vertex_attribs[9], 1);gl_err();
// Instance transform matrix b
glBindBuffer(GL_ARRAY_BUFFER, instance_vertex_buffer_id_a);
glVertexAttribPointer(vertex_attribs[10], 4, GL_FLOAT, GL_FALSE, sizeof(mygl::Particle), (void *)0);gl_err();
glEnableVertexAttribArray(vertex_attribs[10]);gl_err();
glVertexAttribPointer(vertex_attribs[11], 4, GL_FLOAT, GL_FALSE, sizeof(mygl::Particle), (void *)(1 * vec4_size));gl_err();
glEnableVertexAttribArray(vertex_attribs[11]);gl_err();
glVertexAttribPointer(vertex_attribs[12], 4, GL_FLOAT, GL_FALSE, sizeof(mygl::Particle), (void *)(2 * vec4_size));gl_err();
glEnableVertexAttribArray(vertex_attribs[12]);gl_err();
glVertexAttribPointer(vertex_attribs[13], 4, GL_FLOAT, GL_FALSE, sizeof(mygl::Particle), (void *)(3 * vec4_size));gl_err();
glEnableVertexAttribArray(vertex_attribs[13]);gl_err();
// Instance velocity vector b
glVertexAttribPointer(vertex_attribs[14], 3, GL_FLOAT, GL_FALSE, sizeof(mygl::Particle), (void *)(offsetof(mygl::Particle, velocity_)));gl_err();
glEnableVertexAttribArray(vertex_attribs[14]);gl_err();
// Instance rotation angle b
glVertexAttribIPointer(vertex_attribs[15], 1, GL_UNSIGNED_INT, sizeof(mygl::Particle), (void *)(offsetof(mygl::Particle, flock_)));gl_err();
glEnableVertexAttribArray(vertex_attribs[15]);gl_err();
glVertexAttribDivisor(vertex_attribs[10], 1);gl_err();
glVertexAttribDivisor(vertex_attribs[11], 1);gl_err();
glVertexAttribDivisor(vertex_attribs[12], 1);gl_err();
glVertexAttribDivisor(vertex_attribs[13], 1);gl_err();
glVertexAttribDivisor(vertex_attribs[14], 1);gl_err();
glVertexAttribDivisor(vertex_attribs[15], 1);gl_err();
glBindBuffer(GL_ARRAY_BUFFER, 0);gl_err();
glBindVertexArray(0);gl_err();
}
void ParticleSystem::print_ssbo()
{
if (iteration_parity == 0)
{
print_buffer("A", particles_a_);
print_sorted("A", particles_a_);
}
else
{
print_buffer("B", particles_b_);
print_sorted("B", particles_b_);
}
}
void ParticleSystem::retrieve_ssbo()
{
glGetNamedBufferSubData(ssbo_a_, 0, particles_a_.size() * sizeof(Particle), particles_a_.data());
gl_err();
glGetNamedBufferSubData(ssbo_b_, 0, particles_b_.size() * sizeof(Particle), particles_b_.data());
gl_err();
}
void ParticleSystem::print_buffer(std::string name, std::vector<mygl::Particle> buffer)
{
size_t grid_width = N_x_;
std::cout << "\nBuffer: " << name << "\n";
for (size_t y = 0; y < N_y_; y++)
{
std::cout << "[";
for (size_t x = 0; x < N_x_; x++)
{
std::cout
<< "[" << buffer[x + grid_width * y].transform_ << "] ";
//<< ":" << buffer[x + grid_width * y].velocity_ << "] ";
}
std::cout << "]\n";
}
std::cout << "\n\n";
for (size_t y = 0; y < N_y_; y++)
{
std::cout << "[";
for (size_t x = 0; x < N_x_; x++)
{
std::cout
<< "[" << buffer[x + grid_width * y].velocity_ << "] ";
//<< ":" << buffer[x + grid_width * y].velocity_ << "] ";
}
std::cout << "]\n";
}
std::cout << "\n\n";
for (size_t y = 0; y < N_y_ * N_x_ * N_z_; y++)
{
std::cout << "[";
//for (size_t x = 0; x < N_x_; x++)
//{
std::cout
<< "[" << buffer[y].flock_ << "] ";
//<< ":" << buffer[x + grid_width * y].velocity_ << "] ";
//}
std::cout << "]\n";
}
}
void ParticleSystem::print_sorted(std::string name, std::vector<mygl::Particle> buffer)
{
std::cout << "\nBuffer: " << name << "\n";
if (check_sorted(buffer))
{
std::cout << "SORTED.\n";
}
else
{
std::cout << "NOT SORTED.\n";
}
}
bool ParticleSystem::check_sorted(std::vector<mygl::Particle> buffer)
{
size_t grid_width = N_x_;
bool sorted = true;
for (size_t y = 0; y < N_y_ - 1; y++)
{
for (size_t x = 0; x < N_x_ - 1; x++)
{
if (buffer[(x + 1) + grid_width * y].pos()[0]
< buffer[x + grid_width * y].pos()[0])
{
sorted = false;
}
else if (buffer[x + grid_width * (y + 1)].pos()[2]
< buffer[x + grid_width * y].pos()[2])
{
sorted = false;
}
else if (buffer[(x + 1) + grid_width * y].pos()[0]
== buffer[x + grid_width * y].pos()[0]
&& buffer[(x + 1) + grid_width * y].pos()[2]
< buffer[x + grid_width * y].pos()[2])
{
sorted = false;
}
else if (buffer[x + grid_width * (y + 1)].pos()[2]
== buffer[x + grid_width * y].pos()[2]
&& buffer[x + grid_width * (y + 1)].pos()[0]
< buffer[x + grid_width * y].pos()[0])
{
sorted = false;
}
}
}
return sorted;
}
void ParticleSystem::init_particles()
{
std::cout << "Init boids with " << N_ << " agents.\n";
particles_a_.resize(N_);
particles_b_.resize(N_);
auto grid_center = mygl::Vec3{{0.0, 0.0, 0.0}};
float offset = 5.0f;
size_t grid_width = N_x_;
size_t grid_length = N_y_;
size_t grid_height = offset * (grid_width - 1);
for (auto y = 0u; y < N_y_; ++y)
{
for (auto x = 0u; x < N_x_;++x)
{
for (auto z = 0u; z < N_z_; z++)
{
auto pos = grid_center
- mygl::Vec3{{grid_height / 2.0f, grid_height / 2.0f, grid_height / 2.0f}}
+ mygl::Vec3{{x * offset, z * offset, y * offset}};
auto transform = mygl::matrix4();
transform.translate(pos);
transform.rotate(Vec3{{0.0f, 0.0f, 0.0f}});
transform = transform.transpose();
auto vel = Vec3{{0.0f, 0.0f, 6.0f}};
auto p = Particle(transform, vel, (GLuint)(z % 4));
particles_a_[x + grid_width * y + grid_width * grid_length * z] = p;
particles_b_[x + grid_width * y + grid_width * grid_length * z] = p;
}
}
}
}
void ParticleSystem::render(float deltatime)
{
glBindVertexArray(vao_);
GLint parity_id;
if (sort_prog_ != nullptr)
{
sort_prog_->use();
GLint step_id;
parity_id = glGetUniformLocation(sort_prog_->prog_id(), "parity");gl_err();
glUniform1ui(parity_id, iteration_parity);gl_err();
step_id = glGetUniformLocation(sort_prog_->prog_id(), "sortStep");gl_err();
//std::cout << "====================\n";
//do
//{
//std::cout << "Execute sort.\n";
glBindVertexArray(vao_);
gl_err()
glUniform1ui(step_id, 0);gl_err();
glDispatchCompute(N_x_, N_y_, N_z_);
gl_err();
glUniform1ui(step_id, 1);gl_err();
glMemoryBarrier(GL_ALL_BARRIER_BITS);
glDispatchCompute(N_x_, N_y_, N_z_);
gl_err();
glUniform1ui(step_id, 2);gl_err();
glMemoryBarrier(GL_ALL_BARRIER_BITS);
glDispatchCompute(N_x_, N_y_, N_z_);
gl_err();
glUniform1ui(step_id, 3);gl_err();
glMemoryBarrier(GL_ALL_BARRIER_BITS);
glDispatchCompute(N_x_, N_y_, N_z_);
gl_err();
glUniform1ui(step_id, 4);gl_err();
glMemoryBarrier(GL_ALL_BARRIER_BITS);
glDispatchCompute(N_x_, N_y_, N_z_);
gl_err();
glUniform1ui(step_id, 5);gl_err();
glMemoryBarrier(GL_ALL_BARRIER_BITS);
glDispatchCompute(N_x_, N_y_, N_z_);
gl_err();
glMemoryBarrier(GL_ALL_BARRIER_BITS);
//if (N_x_ * N_y_ <= 1000)
// retrieve_ssbo();
//print_ssbo();
//} while (N_x_ * N_y_ <= 1000 and not check_sorted(iteration_parity == 0 ? particles_a_ : particles_b_));
glBindVertexArray(0);
gl_err();
//print_ssbo();
}
// Run compute program
compute_prog_->use();
auto time = glutGet(GLUT_ELAPSED_TIME);
GLint time_id;
time_id = glGetUniformLocation(compute_prog_->prog_id(), "time");gl_err();
glUniform1f(time_id, time);gl_err();
GLint deltatime_id = glGetUniformLocation(compute_prog_->prog_id(), "deltatime");gl_err();
glUniform1f(deltatime_id, deltatime);gl_err();
parity_id = glGetUniformLocation(compute_prog_->prog_id(), "parity");gl_err();
glUniform1ui(parity_id, iteration_parity);gl_err();
iteration_parity = (iteration_parity + 1) % 2;
glBindVertexArray(vao_);gl_err();
glDispatchCompute(N_x_, N_y_, N_z_);gl_err();
glMemoryBarrier(GL_ALL_BARRIER_BITS);
glBindVertexArray(0);gl_err();
retrieve_ssbo();
//print_ssbo();
//std::cout << "===================\n";
// Run display program
display_prog_->use();
glBindVertexArray(vao_);gl_err()
glDrawArraysInstanced(GL_TRIANGLES, 0, particle_mesh_->verts.size() * 3, N_);gl_err()
glBindVertexArray(0);gl_err()
}
}
<file_sep>/src/mygl/particle_system.h
#ifndef PARTICLE_SYSTEM_H
#define PARTICLE_SYSTEM_H
#include <cstddef>
#include <memory>
#include <vector>
#include <GL/glew.h>
#include "mygl/gl_err.h"
#include "mygl/program/Program.h"
#include "utils/vector.h"
#include "assets/mesh.h"
namespace mygl
{
struct Particle
{
public:
Particle() = default;
Particle(const mygl::matrix4& transform): transform_(transform) {}
Particle(const mygl::matrix4& tranform, const mygl::Vec3& velocity): transform_(tranform), velocity_(velocity) {}
Particle(const mygl::matrix4& tranform, const mygl::Vec3& velocity,
GLuint flock): transform_(tranform), velocity_(velocity),
flock_(flock){}
mygl::matrix4 transform_;
mygl::Vec3 velocity_;
GLuint flock_;
mygl::Vec3 pos() const;
};
class ParticleSystem
{
public:
ParticleSystem() = default;
void init_system(size_t N, mygl::Program* display_prog, mygl::Program* compute_prog, std::shared_ptr<mygl::mesh> mesh);
void init_system(size_t N, mygl::Program* display_prog,
mygl::Program* compute_prog,
mygl::Program* sort_prog,
std::shared_ptr<mygl::mesh> mesh);
void render(float deltatime);
void init_particles();
private:
void retrieve_ssbo();
void print_buffer(std::string name, std::vector<mygl::Particle> buffer);
bool check_sorted(std::vector<mygl::Particle> buffer);
void print_sorted(std::string name, std::vector<mygl::Particle> buffer);
void print_ssbo();
private:
mygl::Program* display_prog_;
mygl::Program* compute_prog_;
mygl::Program* sort_prog_;
GLuint vao_;
size_t N_;
size_t N_x_;
size_t N_y_;
size_t N_z_;
std::shared_ptr<mygl::mesh> particle_mesh_;
std::vector<mygl::Particle> particles_a_;
GLuint ssbo_a_;
std::vector<mygl::Particle> particles_b_;
GLuint ssbo_b_;
unsigned iteration_parity = 0;
};
}
#endif //PARTICLE_SYSTEM_H
<file_sep>/src/mygl/basicmovable.cpp
//
// Created by defalur on 17/06/20.
//
#include "basicmovable.h"
void BasicMovable::set_pos(mygl::Vec3 p)
{
pos = p;
}
void BasicMovable::translate(mygl::Vec3 v)
{
pos += v;
}
void BasicMovable::translate_local(mygl::Vec3 v)
{
auto translation = v[0] * left + v[1] * (forward ^ left).normalized() + v[2] * forward;
pos += translation;
}
void BasicMovable::set_rot(mygl::Vec3 r)
{
}
void BasicMovable::rotate(mygl::Vec3 r)
{
}
mygl::Vec3 BasicMovable::get_pos()
{
return pos;
}
<file_sep>/src/crowd_sim.cpp
#include <iostream>
#include "GL/glew.h"
#include <GL/freeglut.h>
#include <array>
#include <mygl/program/programbuilder.h>
#include <mygl/shadertypes.h>
#include "assets/material.h"
#include "assets/scene.h"
#include "mygl/assets/mesh.h"
#include "assets/cameratracking.h"
#include "assets/skybox.h"
#include "mygl/particle_system.h"
#include "mygl/basicmovable.h"
#include "mygl/gl_err.h"
#include "mygl/inputmanager.h"
#include "mygl/program/Program.h"
#include "trajectory/trajectory.h"
#include "utils/clock.h"
#include "utils/matrix4.h"
mygl::ParticleSystem particle_system;
mygl::Skybox skybox;
std::function<void()> light_trajectory_callback;
std::function<void()> cam_trajectory_callback;
void display()
{
glClearColor(0.95f, 0.93f, 0.9f, 1.0f) ;
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);gl_err();
particle_system.render(mainClock.deltatime());
skybox.render(mainClock.deltatime());
glutSwapBuffers();
inputManager.send_mouse_input();
inputManager.send_keyboard_input();
mainClock.tick();
}
void mouseClick(int button, int state, int, int)
{
inputManager.set_mouse_type(button, state);
}
void mouseMove(int x, int y)
{
inputManager.set_mouse_coords(x, y);
}
void keyDown(unsigned char key, int, int)
{
inputManager.set_key(key, true);
}
void keyUp(unsigned char key, int, int)
{
inputManager.set_key(key, false);
}
void refresh_timer(int)
{
glutPostRedisplay();
//light_trajectory_callback();
//cam_trajectory_callback();
glutTimerFunc(1000/50, refresh_timer, 0);
}
bool initGlut(int &argc, char **argv) {
glutInit(&argc, argv);
glutInitContextVersion(4, 5);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);
glutInitWindowSize(1900, 1000);
glutInitWindowPosition(10, 10);
glutCreateWindow("Crowd Simulation");
glutDisplayFunc(display);
glutMouseFunc(mouseClick);
glutMotionFunc(mouseMove);
glutPassiveMotionFunc(mouseMove);
glutKeyboardFunc(keyDown);
glutKeyboardUpFunc(keyUp);
glutSetKeyRepeat(GLUT_KEY_REPEAT_OFF);
return true;//thanks, now I can really test for errors
}
bool initGlew() {
return (glewInit() == GLEW_OK);
}
bool init_gl()
{
glEnable(GL_DEPTH_TEST);gl_err();
glDepthFunc(GL_LESS);gl_err();
glDepthRange(0.0, 1.0);gl_err();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);gl_err();
glEnable(GL_CULL_FACE);gl_err();
glCullFace(GL_FRONT);gl_err();
glFrontFace(GL_CCW);gl_err();
glClearColor(0.0, 0.0, 0.0, 1);gl_err();
return true;
}
void init_color_uniform(mygl::Program* prog, std::array<float, 4> color)
{
GLint color_id;
color_id = glGetUniformLocation(prog->prog_id(), "color");gl_err();
glUniform4f(color_id, color[0], color[1], color[2], color[3]);gl_err();
}
int main(int argc, char **argv)
{
if (argc != 2)
{
std::cout << "usage error: number of particles required\n";
return 1;
}
initGlut(argc, argv);
initGlew();
init_gl();
std::string v_shader = "../shaders/particle_vertex.shader";
std::string f_shader = "../shaders/particle_fragment.shader";
std::string skybox_v_shader = "../shaders/skybox_vertex.shader";
std::string skybox_f_shader = "../shaders/skybox_fragment.shader";
std::string c_shader = "../shaders/boids.shader";
std::string sort_shader = "../shaders/spatial_sort.shader";
auto prog_builder = mygl::ProgramBuilder{};
prog_builder.add_shader(
mygl::shaders::DisplayShadersBase{v_shader, f_shader}
);
auto skybox_prog_builder = mygl::ProgramBuilder{};
skybox_prog_builder.add_shader(
mygl::shaders::DisplayShadersBase{skybox_v_shader, skybox_f_shader}
);
auto compute_prog_builder = mygl::ProgramBuilder{};
compute_prog_builder.add_shader(
mygl::shaders::ComputeShader{c_shader}
);
auto sort_prog_builder = mygl::ProgramBuilder{};
sort_prog_builder.add_shader(
mygl::shaders::ComputeShader{sort_shader}
);
auto prog_result = prog_builder.build();
auto skybox_result = skybox_prog_builder.build();
auto compute_result = compute_prog_builder.build();
auto sort_result = sort_prog_builder.build();
if (prog_result == std::nullopt || skybox_result == std::nullopt
|| compute_result == std::nullopt
|| sort_result == std::nullopt)
{
std::cout << "Shader compilation failed.\n";
return 1;
}
auto prog = prog_result->get();
auto skybox_prog = skybox_result->get();
auto compute_prog = compute_result->get();
prog->use();
//init camera
auto cam = std::make_shared<Camera>(-1, 1, -1, 1, 5, 20000);
cam->add_prog(prog);
cam->look_at({{0, 0, 10}}, {{0, 0, 0}}, {{0, 1, 0}});
cam->set_prog_proj(prog);
inputManager.register_mouse_listener(cam);
inputManager.register_keyboard_listener(cam);
auto lights = LightManager{};
lights.set_directional(0, {{5,5,5}}, {{0, 0, 0}}, {{1,1,0.8}});
lights.set_ambient(1, {{0,0,0}}, 0.2 * mygl::Vec3({1,1,1}));
lights.set_lights_uniform(prog);
init_color_uniform(prog, {{0.6, 0.8, 0.9, 1}});
// Setup skybox program
skybox_prog->use();
skybox.init_skybox(skybox_prog, "../textures/skybox");
cam->add_prog(skybox_prog);
cam->set_prog_proj(skybox_prog);
// Load particle mesh
auto mesh = mygl::load_mesh("../meshes/fish.obj");
// Load texture
auto material = Material(std::make_shared<TextureManager>(), prog, "../textures/fish_uv.tga");
material.use();
particle_system.init_system(std::stoul(std::string(argv[1])), prog, compute_prog, sort_result->get(), mesh);
//start display timer and start main loop
glutTimerFunc(1000/50, refresh_timer, 0);
glutMainLoop();
return 0;
}
<file_sep>/src/mygl/gl_err.h
#ifndef BUMP_GL_ERR_H
#define BUMP_GL_ERR_H
#include <iostream>
#define gl_err() \
{\
GLenum err = glGetError();\
if (err != GL_NO_ERROR) std::cerr << "OpenGL error in file "<< __FILE__ <<" l." << __LINE__ << ": " << err << std::endl;\
}
#endif //BUMP_GL_ERR_H
|
6d4ca2c2bc54eac0d35a1d010d91d8c2386adec7
|
[
"CMake",
"C++"
] | 11
|
CMake
|
mattrouss/pogla
|
c01f63bb83d5e499d5d7e6d97cea2ee1a790f62d
|
c2513568f7fb052677af866e7bd89a040ec579ac
|
refs/heads/master
|
<repo_name>vlk3/PUBPOL590<file_sep>/GroupAssignment4Kan.py
from __future__ import division
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import os
main_dir = "/Users/Vivian/Desktop/Data/Group Assignment 4/"
#CHANGE WORKING DIRECTORY (wd)
os.chdir(main_dir)
from logit_functions import *
## ***SECTION 0*** ##
#IMPORT DATA
df = pd.read_csv(main_dir + '14_B3_EE_w_dummies.csv')
df = df.dropna(axis=0, how='any')
#GET TARIFF
tariffs = [v for v in pd.unique(df['tariff']) if v != 'E']
stimuli = [v for v in pd.unique(df['stimulus']) if v != 'E']
tariffs.sort()
stimuli.sort()
# RUN LOGIT-------------
drop = [v for v in df.columns if v.startswith("kwh_2010")]
df_pretrial = df.drop(drop, axis=1)
for i in tariffs:
for j in stimuli:
# dummy variables must start with "D_" and consumption variables with "kwh_"
logit_results, df_logit = do_logit(df_pretrial, i, j, add_D=None, mc=False)
#QUICK MEANS COMPARISON WITH T-TEST BY HAND------------
#creat means
grp = df_logit.groupby('tariff')
df_mean = grp.mean().transpose()
df_mean.B - df_mean.E
# do a t-test "by hand"
df_s = grp.std().transpose()
df_n = grp. count().transpose().mean()
top = df_mean['B'] - df_mean['E']
bottom = np.sqrt(df_s['B']**2/df_n['B'] + df_s['E']**2/df_n['E'])
tstats = top/bottom
sig = tstats[np.abs(tstats) > 2]
sig.name = 't-stats'
##------------------------------------------------------------------------------------------------------------------##
## ***SECTION 1*** ## Repeat Section 0 with new data set; test for imbalance running Logit and a "Quick Means Comparison"
#IMPORT DATA
df = pd.read_csv(main_dir + 'task_4_kwh_w_dummies_wide.csv')
df = df.dropna(axis=0, how='any')
#GET TARIFF
tariffs = [v for v in pd.unique(df['tariff']) if v != 'E']
stimuli = [v for v in pd.unique(df['stimulus']) if v != 'E']
tariffs.sort()
stimuli.sort()
# RUN LOGIT-------------
drop = [v for v in df.columns if v.startswith("kwh_2010")]
df_pretrial = df.drop(drop, axis=1)
for i in tariffs:
for j in stimuli:
# dummy variables must start with "D_" and consumption variables with "kwh_"
logit_results, df_logit = do_logit(df_pretrial, i, j, add_D=None, mc=False)
#QUICK MEANS COMPARISON WITH T-TEST BY HAND------------
#creat means
grp = df_logit.groupby('tariff')
df_mean = grp.mean().transpose()
df_mean.B - df_mean.E
# do a t-test "by hand"
df_s = grp.std().transpose()
df_n = grp. count().transpose().mean()
top = df_mean['B'] - df_mean['E']
bottom = np.sqrt(df_s['B']**2/df_n['B'] + df_s['E']**2/df_n['E'])
tstats = top/bottom
sig = tstats[np.abs(tstats) > 2]
sig.name = 't-stats'
<file_sep>/Assignment1/data/Assignment1Kan.py
# Using Series and DataFrame from pandas; shorthand for pandas and numpy
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
#Setting up the file path (quotations marks are important especially because there are spaces in my path
main_dir = "/Users/Vivian/MPP Fall 2014 & Spring 2015/Big Data/GitHub/PUBPOL590"
txt_file = "/Assignment1/data/File1_small.txt"
# First step: import the data from github
## Then create a dataframe, df, by importing data using panda
# Don't forget to indicate that it's spaced delimited
pd.read_table(main_dir + txt_file, sep = " ")
df = pd.read_table(main_dir + txt_file, sep = " ")
list(df) # this tells you the column name
# ROW SLICING
## slicing -- using `:` in a data frame
df[60:100]
# Electricity consumption greater than 30
df.kwh > 30
df[df.kwh >30] <file_sep>/Inclass Practice Feb18.py
from __future__ import division
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
main_dir = "/Users/Vivian/Desktop/Data/"
root = main_dir + "Inclass Data/data/"
# PATHING --------------
paths = [os.path.join(root,v) for v in os.listdir(root) if v.startswith("file_")]
# IMPORT AND STACK ---------
df = pd.concat([pd.read_csv(v, names = ['panid', 'date', 'kwh'], parse_dates = [1], header=0) for v in paths],
ignore_index = True) #the parse_date changes the format of how the date column [1] is presented in the dataframe
df_assign = pd.read_csv(root + "sample_assignments.csv", usecols = [0,1])
# MERGE ---------
df = pd.merge(df, df_assign)
#TO SORT
df.sort(['date'])
# GROUPBY aka "split, apply, combine"
## see more at http://pandas.pydata.org/pandas-docs/stable/groupby.html
grp1 = df.groupby(['assignment']) # .groupby objects for big data
gd1 = grp1.groups # CAUTION! don't do this with super big data. it will crash.
## peek inside gd1 (dictionary)
gd1.keys()
gd1['C'] # gd1 is a dict, so must use keys to get data
gd1.values()[0] # gd1.values() is a list, so we can use numerical indeces
gd1.viewvalues() # see all the values of the dictionary, gd1
## iteration properties of a dictionary
[v for v in gd1.itervalues()]
gd1.values() # equivalent to above
[k for k in gd1.iterkeys()]
gd1.keys() # equivalent
[(k,v) for k,v in gd1.iteritems()]
gd1
## split and apply (pooled data)
grp1['kwh'].mean()
## split and apply (panel/time series data)
grp2 = df.groupby(['assignment','date'])
gd2 = grp2.groups
gd2 # look at the dictionary (key, value) pairs
grp2['kwh'].mean() ## this doesn't help with cross comparison of treatment and control, though.
## TESTING FOR BALANCE (OVER-TIME)
from scipy.stats import ttest_ind
## ex using ttest_ind
a = [1, 4, 9, 2]
b = [1, 7, 8, 9]
t, p = ttest_ind(a, b, equal_var = False)
# set up data
grp = df.groupby(['assignment', 'date'])
# get separate sets of treatment and control values by date
trt = {k[1]: df.kwh[v].values for k, v in grp.groups.iteritems() if k[0] == 'T'}
ctrl = {k[1]: df.kwh[v].values for k, v in grp.groups.iteritems() if k[0] == 'C'}
keys = trt.keys()
## craete dataframe of this information
tstats = DataFrame([(k, np.abs(ttest_ind(trt[k], ctrl[k], equal_var=False)[0])) for k in keys],
columns = ['date', 'tstat']) #abs stands for absolute value; ind is individual level
pvals = DataFrame([(k, np.abs(ttest_ind(trt[k], ctrl[k], equal_var=False)[1])) for k in keys],
columns = ['date', 'pval'])
t_p = pd.merge(tstats, pvals)
## sort the t_p and reset_index
t_p.sort(['date'], inplace=True) ##need the inplace=True because it sorts AND overwrite; think about Excel sorting
t_p.reset_index(inplace=True, drop=True) # drop=True will drop the old index column!
## PLOTTING----------------
fig1 = plt.figure() ##initializing plot
ax1 = fig1.add_subplot(2,1,1) ## (number or row you want, column you want, and first plot)
ax1.plot(t_p['tstat'])
ax1.axhline(2, color='r', linestyle='--')
ax2= fig1.add_subplot(2,1,2) #two rows, one column, first plot
ax2.plot(t_p['pval'])
ax2.axhline(0.05, color='r', linesytle='--')
plt.show()
#use plt.plot? for help
<file_sep>/GroupAssignment2Kan.py
from __future__ import division
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
from scipy.stats import ttest_ind
main_dir = "/Users/Vivian/Desktop/Data/"
root = main_dir + "Group Assignment/"
# PATHING----------------------
paths = [os.path.join(root, v) for v in os.listdir(root) if v.startswith("File")]
# IMPORT AND STACK--------------------
df = pd.concat([pd.read_table(v, skiprows = 6000000, nrows = 1500000, sep = " ", names = ['ID', 'DAYHH', 'kwh']) for v in paths], ignore_index = True)
df_allocation = pd.read_csv(root + "SME and Residential allocations.csv",usecols = ['ID','Code','Residential - Tariff allocation','Residential - stimulus allocation'],na_values = ['-', 'NA', 'NULL', '', '.'])
df2 = df_allocation.rename(columns = {'Residential - Tariff allocation':'RES_Tariff','Residential - stimulus allocation':'RES_Stimulus'})
# Trimming data before merging
df2 = df2[df2.Code <=1] # this will keep only Residnetial Home under "Code"
df2[(df2['RES_Tariff'] == 'A') & (df2['RES_Stimulus']== '1') | (df2['RES_Stimulus']== 'E')]
#Keep only Tariff A and Bi-monthly (1) stimulus or the Control (E)
df2 = df2[(df2['RES_Tariff'] == 'A') & (df2['RES_Stimulus']== '1') | (df2['RES_Stimulus']== 'E')]
df = pd.merge(df, df2, on = 'ID')
# Can use df.sort[('')] to check to make sure all the tariff and stimulus groups are represented. I'm sure there's an easier way... oh well
## Splitting the DAYHH column into Day and HH
df['hour_cer'] = df['DAYHH'] %100
df['day_cer'] = (df['DAYHH']-df['hour_cer']% 100)/100
df = df[['ID', 'DAYHH', 'hour_cer', 'day_cer', 'kwh', 'Code', 'RES_Tariff', 'RES_Stimulus']]
# IMPORTING TS Correction
df_correction = pd.read_csv(root + "timeseries_correction.csv", usecols = ['hour_cer', 'day_cer','date', 'year', 'month', 'day'])
# CER ANOMOLY CORRECTION
## see http://pandas.pydata.org/pandas-docs/stable/indexing.html#advanced-indexing-with-labels
df_correction.ix[df_correction['day_cer'] == 452, 'hour_cer'] = np.array([v for v in range(1,49) if v not in [2,3]])
df3 = pd.merge(df, df_correction, on= ['hour_cer','day_cer'])
# DAILY AGGREGATION --------------------
grp = df3.groupby(['ID','day_cer', 'RES_Stimulus']) #this helps agg the kwh consumption for every HH
agg = grp['kwh'].sum()
grp.sum()
# reset the index (multilevel at the moment)
agg = agg.reset_index() # drop the multi-index
grp1 = agg.groupby(['day_cer','RES_Stimulus']) #reducing the amount of groups and increasing thel list size; we are distinguishing them by assignemtn, not HH
#agg.head() to look at first five rows
## split up treatment/control
trt = {(k[0]): agg.kwh[v].values for k, v in grp1.groups.iteritems() if k[1] == '1'} # get set of all treatments by date
ctrl = {(k[0]): agg.kwh[v].values for k, v in grp1.groups.iteritems() if k[1] == 'E'} # get set of all controls by date
keys = ctrl.keys()
# tstats and pvals
tstats = DataFrame([(k, np.abs(float(ttest_ind(trt[k], ctrl[k], equal_var=False)[0]))) for k in keys], columns=['day_cer', 'tstat'])
pvals = DataFrame([(k, (ttest_ind(trt[k], ctrl[k], equal_var=False)[1])) for k in keys], columns=['day_cer', 'pval'])
t_p = pd.merge(tstats, pvals)
#Plotting!
fig1 = plt.figure() # initialize plot
ax1 = fig1.add_subplot(2,1,1) # two rows, one column, first plot
ax1.plot(t_p['day_cer'],t_p['tstat'])
ax1.axhline(2, color='r', linestyle='--')
ax1.axvline(180, color='g', linestyle='--')
ax1.set_title('t-stats over-time (daily)')
ax2 = fig1.add_subplot(2,1,2) # two rows, one column, first plot
ax2.plot(t_p['day_cer'], t_p['pval'])
ax2.axhline(0.05, color='r', linestyle='--')
ax2.axvline(180, color='g', linestyle='--')
ax2.set_title('p-values over-time (daily)')
plt.show()
# MONTHLY AGGREGATION
grp2 = df3.groupby(['ID','year','month','RES_Stimulus']) ## Dan said to group by year and month
agg1 = grp2['kwh'].sum()
# reset the index (multilevel at the moment)
agg1 = agg1.reset_index() # drop the multi-index
grp3 = agg1.groupby(['year', 'month', 'RES_Stimulus'])
#agg.head() to look at first five rows
## split up treatment/control
trt1 = {(k[0], k[1]): agg1.kwh[v].values for k, v in grp3.groups.iteritems() if k[2] == '1'} # get set of all treatments by year-month
ctrl1 = {(k[0], k[1]): agg1.kwh[v].values for k, v in grp3.groups.iteritems() if k[2] == 'E'} # get set of all controls by year-month
keys2 = ctrl1.keys()
# tstats and pvals
tstats1 = DataFrame([(k, np.abs(float(ttest_ind(trt1[k], ctrl1[k], equal_var=False)[0]))) for k in keys2], columns=['month', 'tstat1'])
pvals1 = DataFrame([(k, (ttest_ind(trt1[k], ctrl1[k], equal_var=False)[1])) for k in keys2], columns=['month', 'pval1'])
t_p1 = pd.merge(tstats1, pvals1)
#Plotting!
fig2 = plt.figure() # initialize plot
ax3 = fig2.add_subplot(2,1,1) # two rows, one column, first plot
ax3.plot(t_p1['tstat1'])
ax3.axhline(2, color='r', linestyle='--')
ax3.axvline(6, color='g', linestyle='--')
ax3.set_title('t-stats over-time (monthly)')
ax4 = fig2.add_subplot(2,1,2) # two rows, one column, first plot
ax4.plot(t_p1['pval1'])
ax4.axhline(0.05, color='r', linestyle='--')
ax4.axvline(6, color='g', linestyle='--')
ax4.set_title('p-values over-time (monthly')
plt.show()
<file_sep>/Groupby_Unstack_inclass.py
from __future__ import division
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import os
main_dir = "/Users/Vivian/Desktop/Data/"
root = main_dir + "Inclass Data/"
## PATHING
paths = [os.path.join(root,v) for v in os.listdir(root) if v.startswith("file_")]
# IMPORT and STACK-------
df = pd.concat([pd.read_csv(v, names = ['panid', 'date', 'kwh']) for v in paths], ignore_index = True)
df_assign = pd.read_csv(root + "sample_assignments.csv", usecols = [0,1])
## MERGE
df = pd.merge(df, df_assign)
#GROUPBY aka "split, apply, combine"
## See Dan's codes
# Split by C/T, pooled w/o time
groups1 = df.groupby(['assignment'])
groups1.groups
# apply the mean
groups1['kwh'].apply(np.mean) #this calculates a pooled mean; time is not a factor; np is numpy
#.apply is to "apply" ANY type of function
groups1['kwh'].mean()
#.mean() is an insternal method, a faster way that produce the same results as Line 30
##DataFrame. + tab or Series. + tab will allow you to see all the internal functions
# Split by Control and Treatment, pooled WITH time
groups2 = df.groupby(['assignment', 'date']) #<-- the order for the 'date' and 'assignment' matters! It affects how to look at the
##data, but the number should be the same
groups2.groups
# apply the mean
groups2['kwh'].mean() #remember, this is mean from pooling accounting for time
# UNSTACK--------
gp_mean = groups2['kwh'].mean()
gp_unstack = gp_mean.unstack('assignment')
gp_unstack['T'] # mean, over time, of all treated panids
<file_sep>/GroupAssignment4Sec1Kan.py
from __future__ import division
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import os
from scipy.stats import ttest_ind
main_dir = "/Users/Vivian/Desktop/Data/Group Assignment 4/"
#CHANGE WORKING DIRECTORY (wd)
os.chdir(main_dir)
from logit_functions import *
## ***SECTION 0*** ##
#IMPORT DATA
df = pd.read_csv(main_dir + '14_B3_EE_w_dummies.csv')
df = df.dropna(axis=0, how='any')
#GET TARIFF
tariffs = [v for v in pd.unique(df['tariff']) if v != 'E']
stimuli = [v for v in pd.unique(df['stimulus']) if v != 'E']
tariffs.sort()
stimuli.sort()
# RUN LOGIT-------------
drop = [v for v in df.columns if v.startswith("kwh_2010")]
df_pretrial = df.drop(drop, axis=1)
for i in tariffs:
for j in stimuli:
# dummy variables must start with "D_" and consumption variables with "kwh_"
logit_results, df_logit = do_logit(df_pretrial, i, j, add_D=None, mc=False)
#QUICK MEANS COMPARISON WITH T-TEST BY HAND------------
#creat means
grp = df_logit.groupby('tariff')
df_mean = grp.mean().transpose()
df_mean.B - df_mean.E
# do a t-test "by hand"
df_s = grp.std().transpose()
df_n = grp. count().transpose().mean()
top = df_mean['B'] - df_mean['E']
bottom = np.sqrt(df_s['B']**2/df_n['B'] + df_s['E']**2/df_n['E'])
tstats = top/bottom
sig = tstats[np.abs(tstats) > 2]
sig.name = 't-stats'
##------------------------------------------------------------------------------------------------------------------##
## ***SECTION 1*** ## Repeat Section 0 with new data set; test for imbalance running Logit and a "Quick Means Comparison"
#IMPORT DATA
df = pd.read_csv(main_dir + 'task_4_kwh_w_dummies_wide.csv')
df = df.dropna(axis=0, how='any')
#GET TARIFF
tariffs = [v for v in pd.unique(df['tariff']) if v != 'E']
stimuli = [v for v in pd.unique(df['stimulus']) if v != 'E']
tariffs.sort()
stimuli.sort()
# RUN LOGIT-------------
drop = [v for v in df.columns if v.startswith("kwh_2010")]
df_pretrial = df.drop(drop, axis=1)
for i in tariffs:
for j in stimuli:
# dummy variables must start with "D_" and consumption variables with "kwh_"
logit_results, df_logit = do_logit(df_pretrial, i, j, add_D=None, mc=False)
#QUICK MEANS COMPARISON WITH T-TEST BY HAND------------
#create means
grp = df_logit.groupby('tariff')
df_mean = grp.mean().transpose()
df_mean.C - df_mean.E
# do a t-test "by hand"
df_s = grp.std().transpose()
df_n = grp. count().transpose().mean()
top = df_mean['C'] - df_mean['E']
bottom = np.sqrt(df_s['C']**2/df_n['C'] + df_s['E']**2/df_n['E'])
tstats = top/bottom
sig = tstats[np.abs(tstats) > 2]
sig.name = 't-stats'
##-----------------------------------------------------------------------------------------------------------##
## SECTION 2 ##
df_logit['p_val'] = logit_results.predict() # get predicted values of the logit model in Section 1
df_logit['trt'] = 0 + (df_logit['tariff'] == 'C') #this generates a treatment variable
df_logit['w'] = np.sqrt((df_logit['trt']/df_logit['p_val']) + (1-df_logit['trt'])/(1-df_logit['p_val'])) #page 46 in Harding PDF;
df_w = df_logit[['ID', 'trt', 'w']] #create smaller dataframe with just IDs, trt, and weights
##-------------------------------------------------------------------------------------------------------##
## SECTION 3 ##
os.chdir(main_dir)
from fe_functions import *
df = pd.read_csv(main_dir + 'task_4_kwh_long.csv')
df = df.dropna(axis=0, how='any')
df2 = pd.merge(df, df_w) # merge df and the smaller dataframe from Section 2
df2['TP'] = df2.trt.apply(str) + df2.trial.apply(str) #generating a trt and trial interaction; refer to 08_logit_and_fixed_effects_models
df2['log_kwh'] = (df2['kwh'] + 1).apply(np.log) # +1 is used to account for zero consumption values
df2['mo_str'] = np.array(["0" + str(v) if v < 10 else str(v) for v in df2['month']]) #0 is for adding a zero in front of January-September
df2['ym'] = df2['year'].apply(str) + "_" + df2['mo_str'] #concatenate to make ym a string
#Set up variables from the merged dataframe (df2)
y = df2['log_kwh']
P = df2['trial'] > 0 #trial indicator; ** COMPARE WITH PEIZHI'S CODES
TP = df2['TP']
w = df2['w']
mu = pd.get_dummies(df2['ym'], prefix = 'ym').iloc[:, 1:-1]
X = pd.concat([TP, P, mu], axis=1)
#Demeaning time!
ids = df2['ID']
y = demean(y, ids)
#Run FE without AND with weights---------------
## WITHOUT WEIGHTS
fe_model = sm.OLS(y, X) # linearly prob model
fe_results = fe_model.fit() # get the fitted values
print(fe_results.summary()) # print pretty results (no results given lack of obs)
# WITH WEIGHTS
## apply weights to data
y = y*w # weight each y
nms = X.columns.values # save column names
X = np.array([x*w for k, x in X.iteritems()]) # weight each X value
X = X.T # transpose (necessary as arrays create "row" vectors, not column)
X = DataFrame(X, columns = nms) # update to dataframe; use original names
fe_w_model = sm.OLS(y, X) # linearly prob model
fe_w_results = fe_w_model.fit() # get the fitted values
print(fe_w_results.summary()) # print pretty results (no results given lack of obs)
<file_sep>/logit_functions.py
# DEFINE FUNCTIONS -----------------
class logit_colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def rm_perf_sep(y, X):
import pandas as pd
import numpy as np
dep = y.copy()
indep = X.copy()
yx = pd.concat([dep, indep], axis = 1)
grp = yx.groupby(dep)
nm_y = dep.name
nm_dum = np.array([v for v in indep.columns if v.startswith('D_')])
DFs = [yx.ix[v,:] for k, v in grp.groups.iteritems()]
kind = np.array([i for i, v in grp.groups.iteritems()]*2)
perf_sep0 = np.ndarray((2, indep[nm_dum].shape[1]),
buffer = np.array([np.linalg.norm(DF[nm_y].values.astype(bool) - v.values) for DF in DFs for k, v in DF[nm_dum].iteritems()]))
perf_sep1 = np.ndarray((2, indep[nm_dum].shape[1]),
buffer = np.array([np.linalg.norm(~DF[nm_y].values.astype(bool) - v.values) for DF in DFs for k, v in DF[nm_dum].iteritems()]))
check = np.vstack([perf_sep0, perf_sep1])==0.
indx = np.where(check)[1] if np.any(check) else np.array([])
if indx.size > 1:
kind = ['failure' if i == 0 else 'success' for i in kind[np.where(check)[0]]]
else:
kind = 'failure' if kind[np.where(check)[0]] == 0 else 'success'
if indx.size > 0:
keep = np.all(np.array([indep.columns.values != i for i in nm_dum[indx]]), axis=0)
nms = [i.encode('utf-8') for i in nm_dum[indx]]
print (logit_colors.FAIL + logit_colors.UNDERLINE +
"\n%s perfectly predict %s.\nVariables and observations removed.\n" + logit_colors.ENDC) % (nms, kind)
# return matrix with perfect predictor colums removed and obs where true
indep1 = indep[np.all(indep[nm_dum[indx]]!=1, axis=1)].ix[:, keep]
dep1 = dep[np.all(indep[nm_dum[indx]]!=1, axis=1)]
return dep1, indep1
else:
return dep, indep
def rm_vif(X):
import numpy as np
import statsmodels.stats.outliers_influence as smso
loop=True
indep = X.copy()
# print indep.shape
while loop:
vifs = np.array([smso.variance_inflation_factor(indep.values, i) for i in xrange(indep.shape[1])])
max_vif = vifs[1:].max()
# print max_vif, vifs.mean()
if max_vif > 30 and vifs.mean() > 10:
where_vif = vifs[1:].argmax() + 1
keep = np.arange(indep.shape[1]) != where_vif
nms = indep.columns.values[where_vif].encode('utf-8') # only ever length 1, so convert unicode
print (logit_colors.FAIL + logit_colors.UNDERLINE +
"\n%s removed due to multicollinearity.\n" + logit_colors.ENDC) % nms
indep = indep.ix[:, keep]
else:
loop=False
# print indep.shape
return indep
## returns logit_results and final DataFrame
def do_logit(df, tar, stim, add_D=None, mc=False):
import pandas as pd
import statsmodels.api as sm
DF = df.copy()
if add_D is not None:
DF = pd.merge(DF, add_D, on = 'ID')
kwh_cols = [v for v in DF.columns.values if v.startswith('kwh')]
dum_cols = [v for v in add_D.columns.values if v.startswith('D_')]
cols = kwh_cols + dum_cols
else:
kwh_cols = [v for v in DF.columns.values if v.startswith('kwh')]
dum_cols = [v for v in DF.columns.values if v.startswith('D_')]
cols = kwh_cols + dum_cols
# DF.to_csv("/Users/dnoriega/Desktop/" + "test.csv", index = False)
# set up y and X
indx = (DF.tariff == 'E') | ((DF.tariff == tar) & (DF.stimulus == stim))
df1 = DF.ix[indx, :].copy() # `:` denotes ALL columns; use copy to create a NEW frame
df1['T'] = 0 + (df1['tariff'] != 'E') # stays zero unless NOT of part of control
# print df1
y = df1['T']
X = df1[cols] # extend list of kwh names
X['const'] = 1 # bug fixed
msg = ("\n\n\n\n\n-----------------------------------------------------------------\n"
"LOGIT where Treatment is Tariff = %s, Stimulus = %s"
"\n-----------------------------------------------------------------\n") % (tar, stim)
print msg
print (logit_colors.FAIL +
"\n\n-----------------------------------------------------------------" + logit_colors.ENDC)
y, X = rm_perf_sep(y, X) # remove perfect predictors
X = rm_vif(X) if mc else X # remove multicollinear vars
print (logit_colors.FAIL +
"-----------------------------------------------------------------\n\n\n" + logit_colors.ENDC)
## RUN LOGIT
logit_model = sm.Logit(y, X) # linearly prob model
logit_results = logit_model.fit(maxiter=1000, method='newton') # get the fitted values
print logit_results.summary() # print pretty results (no results given lack of obs)
return logit_results, DF.ix[X.index, :]
<file_sep>/Assignment2Kan.py
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import os
main_dir = "/Users/Vivian/Desktop/Data"
git_dir = "/Users/Vivian/MPP Fall 2014 & Spring 2015/Big Data/GitHub/PUBPOL590"
csv_file = "small_data_w_missing_duplicated.csv"
df = pd.read_csv(os.path.join(main_dir, csv_file))
#Inspected data and '-' is a placeholder for missing value
missing = ['.', 'NA', 'NULL', '', '-']
df = pd.read_csv(os.path.join(main_dir, csv_file), na_values = missing)
df.isnull() # pandas method to find missing data; if it returns "True" there's a missing value
df.duplicated() # panda method to find duplicates; "True" is a duplicate
df.drop_duplicates() # this drops true duplicates where EVERYTHING is the same; keeps only 1
df['consump'].isnull() #find subset of full rows of data where consump has missing data
rows = df['consump'].isnull()
df.duplicated(subset = ['panid', 'date']) #finding duplicates under panid and date
##need to drop the missing value for the panid and date subset duplicates
df.duplicated(subset= ['panid', 'date'])
df['consump'].dropna(subset= ['panid', 'date'], axis= 0, how = 'any') #if axis = 0 then we're dropping the ROWS with any missing data
df.dropna(subset = ['panid', 'date'], axis = 0, how = 'any')
##After cleaning the date, take the mean of the consump variable
df['consump'].mean()
##SOLUTION##
df1 = df.drop_duplicates()
df1[df1.consump.isnull()] # investigate data where 'consump' is empty (null)
df1[df1.duplicated(['panid', 'date'])] # look at duplicated (first hit from top-bottom) using 'panid' and 'date' as criteria
df1[df1.duplicated(['panid', 'date'], take_last = True)] # same but bottom to top
df2 = df1.drop_duplicates(['panid', 'date'], take_last = True) # this will keep the bottom to top
df2[df2.duplicated(['panid', 'date'])] # check for dups. its empty!<--This checks if you did it correctly
df2.consump.mean() # get mean
<file_sep>/March25InClass.py
from __future__ import division
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import os
import time
import matplotlib.pyplot as plt
import pytz
from datetime import datetime, timedelta
from scipy.stats import ttest_ind
import statsmodels.api as sm
main_dir = "/Users/Vivian/Desktop/Data/"
root = main_dir + "Group Assignment 3/"
# import data-----------------------
df = pd.read_csv(root + "allocation_subsamp.csv")
grp1 = df.groupby(['tariff','stimulus'])
gd1 = grp1.groups
## peek at key
gd1.keys()
#need to convert array to a list?
df_1A = df[(df.stimulus == '1') & (df.tariff == 'A')]
df_1B = df[(df.stimulus == '1') & (df.tariff == 'B')]
df_3A = df[(df.stimulus == '3') & (df.tariff == 'A')]
df_3B = df[(df.stimulus == '3') & (df.tariff == 'B')]
df_E = df[(df.stimulus == 'E')]
# I think this creates the 5 vectors... but not with the ID, it's by the index...
gd1[('A', '1')]
gd1[('B', '1')]
gd1[('A', '3')]
gd1[('B', '3')]
gd1[('E', 'E')]
# SET UP DATA ---------------------
np.random.seed(1789)
#df1 = pd.concat([df_1A, df_1B, df_3A, df_3B, df_E])
ids = df['ID']
#set up tariff and stimulus groups
tariff =
stimulus =
EE =
# Extract sample size with np.random.choice
# GENERATE RANDOM SAMPLE ASSIGNMENTS ------------------------
sample = np.random.choice(df.index, 300, replace = False) #this extracts 300 sample assignments from the main DF
sampleEE = np.random.choice(df_E.ID.values, 300, replace = False).tolist() #this extracts 300 sample assignments from the control group
sample1A = np.random.choice(df_1A.ID.values, 150, replace = False).tolist()
sample1B = np.random.choice(df_1B.ID.values, 50, replace = False).tolist()
sample3A = np.random.choice(df_3A.ID.values, 150, replace = False).tolist()
sample3B = np.random.choice(df_1A.ID.values, 50, replace = False).tolist()
df_sampleEE = pd.DataFrame(sampleEE)
df_sample1A = pd.DataFrame(sample1A)
df_sample1B = pd.DataFrame(sample1B)
df_sample3A = pd.DataFrame(sample3A)
df_sample3B = pd.DataFrame(sample3B)
df_sample = pd.concat([df_sampleEE, df_sample1A, df_sample1B, df_sample3A, df_sample3B])
df_sample.columns = ['ID']
df_redux = pd.read_csv(root + "kwh_redux_pretrail.csv")
df_sampleredux = pd.merge(df_sample, df_redux, on= 'ID')
#Monthly Aggregation
grp = df.groupby['year', 'month', 'ID'])<file_sep>/GroupAssignmentKan.py
from __future__ import division
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import os
main_dir = "/Users/Vivian/Desktop/Data/"
git_dir = "/Users/Vivian/MPP Fall 2014 & Spring 2015/Big Data/GitHub/PUBPOL590"
## ADVANCED PATHING
root = main_dir + "Group Assignment/"
#paths0 = [root + "File" + str(v) + ".txt" for v in range (1,7)]
## Pathing the Pro Way
[v for v in os.listdir(root)]
[os.path.join(root, v) for v in os.listdir(root)]
[root + v for v in os.listdir(root)]
[root + v for v in os.listdir(root) if v.startswith("File")]
[v for v in os.listdir(root) if v.startswith("File")]
paths1= [root + v for v in os.listdir(root) if v.startswith("File")]
## IMPORTING DATA
list_of_dfs = [ pd.read_table(v, skiprows = 6000000, nrows = 1500000, sep = " ", names = ['ID', 'DAYHH', 'kwh'], na_values = ['-', 'NA', 'NULL', '', '.','999999999','9999999']) for v in paths1]
#I think this works
#pd.read_table('/Users/Vivian/Desktop/Data/Group Assignment/File1.txt', skiprows = 6000000, nrows = 1500000, sep = " ", names = ['ID', 'DAYHH', 'kwh'] for v in paths1)
#indicating that the files are space delimited, skips 6 mil and import next 1.5mil, gives you a proper header
#May not actually need this...
# STACK DATA (aka row bind) + EXTRACTING DAYS AND HOURS
df = pd.concat(list_of_dfs, ignore_index = True)
df1 = pd.concat(list_of_dfs, ignore_index = True)
df1['HH'] = df1['DAYHH'] %100
df1 = df1[['ID', 'DAYHH', 'HH', 'kwh']] #this rearrange the columns
cols = list(df1.columns.values) #this gets you the list of columns
#run cols and then df1 to test the rearranged colums; this
# CLEANING DATA
df2 = df1.drop_duplicates(['ID', 'DAYHH']) #no dup observed
df2 = df2[['ID', 'DAYHH', 'HH', 'kwh']]
df2.isnull()
## Finding DLS-affected data
dls = df2[df2['HH'].isin([49, 50])]
#this returns 2822 rows; meaning 2822 observations have hours 49 and 50 due to DLS
## MERGING
df_allocation = pd.read_csv(root + "SME and Residential allocations.csv",usecols = ['ID','Code','Residential - Tariff allocation','Residential - stimulus allocation','SME allocation'],na_values = ['-', 'NA', 'NULL', '', '.'])
df3 = df_allocation.rename(columns = {'Residential - Tariff allocation':'RES_Tariff','Residential - stimulus allocation':'RES_Stimulus', 'SME allocation':'SME'})
df4 = pd.merge(df2, df3, on = 'ID')
#Notes: Code 3 is possibly problematic; refer to codebook
code3 = df4[df4['Code'].isin([3])] # this finds the number of observation with Code 3 in these 9 million rows of data
## cleaning the missing/duplicates
df4.duplicated(['ID','DAYHH'])
df4.drop_duplicates(['ID','DAYHH'])<file_sep>/March4InClass.py
from __future__ import division
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import os
from dateutil import parser # use this to ensure dates are parsed correctly
main_dir = "/Users/Vivian/Desktop/Data/"
root = main_dir + "Inclass Data/data 2/"
# import data-----------------------
df = pd.read_csv(root + "sample_30min.csv", header=0, parse_dates=[1], date_parser=parser.parse) #we imported a function called parser... then there's an internal method called "parse"
df_assign = pd.read_csv(root + "sample_assignments.csv", usecols = [0,1])
# merge
df = pd.merge(df, df_assign)
##add/drop variable
df['year'] = df['date'].apply(lambda x: x.year)
#we're applying a lambda-year function to the date to extract the year out of 'date'.
#We're telling it to go into the date column and apply the "year" function to the entire column
df['month'] = df['date'].apply(lambda x: x.month)
df['day'] = df['date'].apply(lambda x: x.day)
df['ymd'] = df['date'].apply(lambda x: x.date()) #the empty () is important
# daily aggregation
grp = df.groupby(['year', 'month', 'day', 'panid', 'assignment']) #this is the same as the next row
grp = df.groupby(['ymd', 'panid', 'assignment'])
df1 = grp['kwh'].sum().reset_index() #this is doing three things at once: group by kwh, then sum by the group, and then reset the index
# PIVOT DATA----------------------------
#go from long to wide data
##1. Create column names for wide data
# Create strings names and denote consumption and date
# use ternery expression: [true-expr(x) if condition else false-expr(x) for x in list]; this is just a clean way to write a true/false for loop
#df1['day_str'] = ['0' + str(v) if v <10 else str(v) for v in df1['date']] #add '0' to <10; tacking a 0 in front to preserve the order
#df1['kwh_ymd'] = 'kwh_' + df1.year.apply(str) + '_' + df1.month.apply(str) +
# '_' + df1.day_str.apply(str)
df1['kwh_ymd'] = 'kwh_' + df1['ymd'].apply(str) # don't need the "0" because the ymd is already preserving the order
#2. Pivot! aka long to wide
df1_piv = df1.pivot('panid', 'kwh_ymd', 'kwh') #i, j, k aka your row, column, and the value
#clean up for making things pretty
df1_piv.reset_index(inplace=True) #this makes panid its own variable
df1_piv.columns.name = None # getting rid of that kwh_ymd name from that top left corner
# MERGE TIME invariant data-------
df2 = pd.merge(df_assign, df1_piv) #this attaching order looks better
## export data for regression
df2.to_csv(root + "07_kwh_wide.csv", sep = ",", index=False) # not exporting the row index value
<file_sep>/Merging_inclass.py
from __future__ import division ## this always returns a float if it's not a whole number and you use division
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import os
main_dir = "/Users/Vivian/Desktop/Data"
git_dir = "/Users/Vivian/MPP Fall 2014 & Spring 2015/Big Data/GitHub/PUBPOL590"
csv2= "sample_assignments.csv"
csv1= "small_data_w_missing_duplicated.csv"
##IMPORT DATA-----
df1 = pd.read_csv(os.path.join(main_dir, csv1), na_values = ['-', 'NA'])
df2 =pd.read_csv(os.path.join(main_dir, csv2))
# CLEAN DATA---------
##clean df1 (refer back to online demo 03)
df1 = df1.drop_duplicates()
df1 = df1.drop_duplicates(['panid', 'date'], take_last = True)
##clean df2
df2[[0,1]]
df2 = df2[[0,1]] #reassigning df2 to subset#
## COPY DATAFRAMES-------------
df3 = df2 # creates a link/reference (alter df2 DOES affect df3); look at line 33
df4 = df2.copy() #creating a copy (alter df2 does NOT affect df4); this WILL KEEP A COPY no matter what you do to the original; this double your data and probably shouldn't do that with big data
# REPLACING DATA-----------
df2.group.replace(['T', 'C'], [1,0]) #sequence of replacement is important; 1 replaces T and 0 replaces C. But df2 has not been changed.
df2.group = df2.group.replace(['T', 'C'], [1,0]) #the "group" part is important ##Note: can't run this line and the last line together!
df3 ## df2 and df3 are assigned internally to the same dataframe; we changed df2 in the previous two lines, so df3 automatically
##changes as well even though we have explicitly made changes to df3
## MERGING ----------------
pd.merge(df1, df2) #attaching df2 to df1; "many-to-one' merge using the intersection, automatically finds the keys it has in common
## the "key" is the panid here and will merge on panel id
pd.merge(df1, df2, on = ['panid']) #this tells specifically the merging criteria, aka the key
pd.merge(df1, df2, on = ['panid'], how = 'inner') ##this keeps only the intersection of the keys
pd.merge(df1, df2, on = ['panid'], how = 'outer') ##this takes the union of the keys, so that's why it keeps panid 5
df5= pd.merge(df1, df2, on = ['panid'])
## STACKING AND BINDING (aka ROW BINDS AND COLUMN BINDS)-------
df2
df4
## 'row bind'
pd.concat([df2, df4]) # the default is to row bind aka axis = 0
pd.concat([df2, df4], axis = 0) # same as above
pd.concat([df2, df4], axis = 0, ignore_index = True) # 'ignore_index = False' is default; so instead of 0-4, the DF now shows 0-9
## 'column bind'
pd.concat([df2, df4], axis = 1) # same as above
<file_sep>/March18InClass.py
from __future__ import division
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import os
import statsmodels.api as sm
main_dir = "/Users/Vivian/Desktop/Data/"
root = main_dir + "Inclass Data/data318/"
paths = [root + v for v in os.listdir(root) if v.startswith("08_")]
# IMPORT AND ADD/DROP VARIABLES---------------
df = pd.read_csv(paths[1], header=0, parse_dates=[1], date_parser=np.datetime64)
df_assign = pd.read_csv(paths[0], header=0)
df['year'] = df['date'].apply(lambda x: x.year)
df['month'] = df['date'].apply(lambda x: x.month)
# MONTHLY AGGREGATION -----------------------
grp = df.groupby(['year', 'month', 'panid']) #unlike the pivot class, we're only grouping by these year, month, and panid
df = grp['kwh'].sum().reset_index() #running without reset index will be a series instead of a dataframe; reset everytime you use groupby
# PIVOT THE DATA-----------------------
df['mo_str'] = ['0' + str(v) if v < 10 else str(v) for v in df['month']] # adds a 0 in front of months before October
df['kwh_ym'] = 'kwh_' + df.year.apply(str) + "_" + df.mo_str.apply(str) # make a column of info called kwh_year_month
df_piv = df.pivot('panid', 'kwh_ym', 'kwh')
df_piv.reset_index(inplace = True)
df_piv.columns.name = None # for aesthetic reasons
#MERGE THE STATIC VALUES (e.g. assignments)--------------------
df = pd.merge(df_assign, df_piv)
del df_piv, df_assign
# GENERATE DUMMY VARIABLES FROM QUALITATIVE DATA (i.e. categories)
## pd.get_dummies() will make dummy vectors for ALL "object" or "category" types
df1 = pd.get_dummies(df, columns = ['gender'])
df1.drop(['gender_M'], axis = 1, inplace=True)
## SET UP DATA FOR LOGIT----------------
kwh_cols = [v for v in df1.columns.values if v.startswith('kwh')]
kwh_cols = [v for v in kwh_cols if int(v[-2:]) <4] #just look at the last two values of the string "kwh_2015_XX" and compare it to less than 4
##
cols = ['gender_F'] + kwh_cols #here is a list of columns I want
## SET UP Y, X
y = df1['assignment']
X = df1[cols]
X = sm.add_constant(X)
## LOGIT ------------
logit_model = sm.Logit(y,X)
logit_results = logit_model.fit()
print(logit_results.summary()) ## good news, failed to reject null that there are relationship between the static variable; no systematic diff
|
b1e9a374e9d85b9bfbe8945dd340e9e30313c94e
|
[
"Python"
] | 13
|
Python
|
vlk3/PUBPOL590
|
53dbbc07ef7d83cd408c7c50063073eff0374d8c
|
0f082106144979fa9ab4f965045ad031cb6fb6c0
|
refs/heads/master
|
<repo_name>vasgial/Mail-Platform<file_sep>/src/user/DatabaseManager.java
package user;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import user.User;
public class DatabaseManager {
static DatabaseManager dbManager;
private static Connection conn;
DatabaseManager() {
conn=conn();
}
private static Connection conn() {
if(conn==null) {
try {
conn=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/platform_mail?autoReconnect=true&useSSL=false","user","test");
} catch (SQLException e) {
e.printStackTrace();
}
}
return conn;
}
public static DatabaseManager dbManager() {
if(dbManager==null) {
dbManager=new DatabaseManager();
}
return dbManager;
}
public static void close() {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//view messages
public static ArrayList<Message> viewMessages(int id1) {
ArrayList<Message> messages = new ArrayList<Message>();
String viewMessagesSQL = "SELECT * FROM messages WHERE receiver_id=? OR senter_id = ?";
PreparedStatement preparedStatement;
try {
preparedStatement = conn().prepareStatement(viewMessagesSQL);
preparedStatement.setInt(1, id1);
preparedStatement.setInt(2, id1);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
int receiver_id = rs.getInt("receiver_id");
int senter_id = rs.getInt("senter_id");
String dateTime = rs.getString("dateTime");
String text = rs.getString("text");
boolean receiverHasRead = rs.getBoolean("receiverHasRead");
new User();
messages.add(new Message(id, PlatformMail.getUserId(receiver_id) , PlatformMail.getUserId(senter_id) , dateTime, text, receiverHasRead));
//System.out.println(id + " " +PlatformMail.getUsernameFromId(senter_id) + " " + PlatformMail.getUsernameFromId(receiver_id) + " " + dateTime + " " + text + " " );
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return messages;
}
//view users
public static ArrayList<User> getUsers(){
ArrayList<User> users = new ArrayList<User>();
String selectSQL = "select * from users";
PreparedStatement preparedStatement;
try {
preparedStatement = conn().prepareStatement(selectSQL);
ResultSet rs = preparedStatement.executeQuery(selectSQL );
//System.out.println("id " + "username " + "password " + "role " );
while (rs.next()) {
int id = rs.getInt("id");
String username = rs.getString("username");
String password = <PASSWORD>("<PASSWORD>");
String role = rs.getString("role");
new User();
if(role.equals("UserView")) {
users.add(new UserView(id, username, password, role));
}
else if(role.equals("UserViewEdit")) {
users.add(new UserViewEdit(id, username, password, role));
}
else if(role.equals("UserViewEditDelete")) {
users.add(new UserViewEditDelete(id, username, password, role));
}
else {
users.add(new Admin(id, username, password, role));
}
//System.out.println(id + " " + username + " " + password + " " + role);
}
//System.out.println(" ");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return users;
}
//create message
public static void createMessages(String dateTime, String text, int senter_id, int receiver_id) throws SQLException {
String createMessageSQL = "INSERT INTO platform_mail.messages"
+ "(id, dateTime, text, senter_id, receiver_id, receiverHasRead) VALUES"
+ "(null, ?, ?, ?, ?, false)";
PreparedStatement preparedStatement = conn.prepareStatement(createMessageSQL);
preparedStatement.setString(1, dateTime);
preparedStatement.setString(2, text);
preparedStatement.setInt(3, senter_id);
preparedStatement.setInt(4, receiver_id);
preparedStatement.executeUpdate();
}
//create user
public static void createUsers(String username, String password, String role) throws SQLException {
String createUsersSQL = "INSERT INTO platform_mail.users"
+ "(id, username, password, role) VALUES"
+ "(null, ?, ?, ?)";
PreparedStatement preparedStatement = conn.prepareStatement(createUsersSQL);
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
preparedStatement.setString(3, role);
preparedStatement.executeUpdate();
}
//delete message
public static void deleteMessage(int id) throws SQLException {
String deleteMessageSQL = "DELETE FROM messages WHERE id=?";
PreparedStatement preparedStatement = conn.prepareStatement(deleteMessageSQL);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
}
//delete user
public static void deleteUser(int id) throws SQLException {
String deleteUserSQL = "DELETE FROM users WHERE id=?";
PreparedStatement preparedStatement = conn.prepareStatement(deleteUserSQL);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
}
//update message
public static void updateMessage(int id, String text) throws SQLException {
String updateMessageSQL = "UPDATE messages SET text = ? WHERE id = ?";
PreparedStatement preparedStatement = conn.prepareStatement(updateMessageSQL);
preparedStatement.setString(1, text);
preparedStatement.setInt(2, id);
preparedStatement .executeUpdate();
}
//update user
public static void updateUser(String role, int id) {
String updateUserSQL = "UPDATE users SET role = ? WHERE id = ?";
PreparedStatement preparedStatement;
try {
preparedStatement = conn.prepareStatement(updateUserSQL);
preparedStatement.setString(1, role);
preparedStatement.setInt(2, id);
preparedStatement .executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>/src/user/UserView.java
package user;
public class UserView extends User {
public UserView() {
// TODO Auto-generated constructor stub
}
public UserView(int id, String username, String password,String role) {
super(id, username, password, role);
}
}
<file_sep>/src/user/Editable.java
package user;
public interface Editable {
abstract boolean editMessages(int id, String text);
}
<file_sep>/src/user/Received.java
package user;
import java.util.ArrayList;
public class Received {
private ArrayList<Message> messages;
public Received() {
// TODO Auto-generated constructor stub
}
public Received(ArrayList<Message> messages) {
this.messages = messages;
}
public ArrayList<Message> getMessages() {
return messages;
}
public void setMessages(ArrayList<Message> messages) {
this.messages = messages;
}
}
<file_sep>/src/user/UserViewEdit.java
package user;
import java.sql.SQLException;
public class UserViewEdit extends User implements Editable{
public UserViewEdit() {
// TODO Auto-generated constructor stub
}
public UserViewEdit(int id, String username, String password,String role) {
super(id, username, password, role);
}
//update a message
@Override
public boolean editMessages(int id, String text) {
try {
DatabaseManager.updateMessage(id, text);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return false;
}
}
<file_sep>/src/user/Deletable.java
package user;
public interface Deletable {
abstract boolean deleteMessages(int id);
}
<file_sep>/src/user/User.java
package user;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Scanner;
public class User implements ViewCreatable {
private int id;
private String username;
private String password;
private Received received;
private Sent sent;
private String role;
public User() {
// TODO Auto-generated constructor stub
}
public User(String username, String password, Received received, Sent sent, String role) {
this.username = username;
this.password = <PASSWORD>;
this.received = received;
this.sent = sent;
this.role = role;
}
public User(String username, String password, String role) {
this.username = username;
this.password = <PASSWORD>;
this.role = role;
}
public User(int id,String username, String password, String role) {
this.username = username;
this.password = <PASSWORD>;
this.role = role;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return <PASSWORD>;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public Received getReceived() {
return received;
}
public void setReceived(Received received) {
this.received = received;
}
public Sent getSent() {
return sent;
}
public void setSent(Sent sent) {
this.sent = sent;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
//create a message
@Override
public void createMessages(String text, int receiver_id) {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(date);
try {
DatabaseManager.createMessages(currentTime,text, this.id, receiver_id) ;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//view messages
@Override
public boolean viewMessages() {
DatabaseManager.viewMessages(id);
System.out.println();
// TODO Auto-generated method stub
return false;
}
public String toString() {
return "id: " + id + ", username: " + username + ", password: " + <PASSWORD> + ", role:" + role + ". ";
}
public static void writeAction(String username, String action ) {
try {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(date);
String str= currentTime + " " + username + " " + action ;
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Action_User_file.txt", true)));
out.println(str);
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
}
<file_sep>/src/user/Admin.java
package user;
import java.sql.SQLException;
public class Admin extends User implements Editable, Deletable{
public Admin() {
// TODO Auto-generated constructor stub
}
public Admin(int id, String username, String password,String role) {
super(id, username, password, role);
}
public Admin( String username, String password,String role) {
super( username, password, role);
}
//delete message
@Override
public boolean deleteMessages(int id) {
try {
DatabaseManager.deleteMessage(id);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return false;
}
//update message
@Override
public boolean editMessages(int id, String text) {
try {
DatabaseManager.updateMessage(id, text);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return false;
}
//create a user
public void createUsers(String username, String password, String role) {
try {
DatabaseManager.createUsers(username, password, role);
//PlatformMail.getUsers().addAll(PlatformMail.getUsers() );
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//view users
public void viewUsers() {
DatabaseManager.getUsers();
}
//delete a user
public boolean deleteUser(int id) {
try {
DatabaseManager.deleteUser(id);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
//update a user
public boolean updateUser(String role,int id) {
DatabaseManager.updateUser(role, id);
return false;
}
}
<file_sep>/src/user/PlatformMail.java
package user;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
public class PlatformMail {
/*private Admin admin;*/
static ArrayList<User> users;
private static ArrayList<Message> messages;
public PlatformMail() {
downloadUsers();
// TODO Auto-generated constructor stub
}
//save messages into java
public void downloadMessages(int id) {
messages = DatabaseManager.viewMessages(id);
}
//save users into java
public void downloadUsers() {
users = DatabaseManager.getUsers();
}
public static ArrayList<User> getUsers() {
return users;
}
public void setUsers(ArrayList<User> users) {
this.users = users;
}
public static ArrayList<Message> getMessages() {
return messages;
}
public void setMessages(ArrayList<Message> messages) {
this.messages = messages;
}
//if exist username
public boolean exist(String username) {
boolean exi = false;
for(int i=0 ; i<users.size() ; i++) {
if(username.equals(users.get(i).getUsername())) {
exi = true;
break;
}
}
return exi;
}
//if exist message_id
public boolean existMessageId(int id) {
boolean exi = false;
for(int i=0 ; i<messages.size() ; i++) {
if(id == messages.get(i).getId()) {
exi = true;
break;
}
}
return exi;
}
//if exist user_id
public boolean existUserId(int id) {
boolean exi = false;
for(int i=0 ; i<users.size() ; i++) {
if(id == users.get(i).getId()) {
exi = true;
break;
}
}
return exi;
}
//confirm password
public boolean confirm(String username, String password) {
boolean conf = false;
for(int i=0 ; i<users.size() ; i++) {
if(password.equals(users.get(i).getPassword()) && username.equals(users.get(i).getUsername()) ) {
conf = true;
break;
}
}
return conf;
}
public User getUser(String username){
User user = null;
for(int i=0 ; i<users.size() ; i++) {
if(users.get(i).getUsername().equals(username)) {
user = users.get(i);
break;
}
}
return user;
}
public static User getUserId(int id){
User user = null;
for(int i=0 ; i<users.size() ; i++) {
if(users.get(i).getId() ==id) {
user = users.get(i);
break;
}
}
return user;
}
public static String getUsernameFromId(int id) {
for(int i=0 ; i<users.size() ; i++) {
if(users.get(i).getId() ==id) {
return users.get(i).getUsername();
}
}
return null;
}
public static int getMessageIndexFromId(int id) {
for(int i=0 ; i<messages.size() ; i++) {
if(messages.get(i).getId() == id) {
return i;
}
}
return -1;
}
public static void printUsers() {
for(int i=0 ; i<users.size() ; i++) {
System.out.println(users.get(i));
}
}
public static void printMessages() {
for(int i=0 ; i<messages.size() ; i++) {
System.out.println(messages.get(i));
}
}
}
<file_sep>/src/user/UserViewEditDelete.java
package user;
import java.sql.SQLException;
public class UserViewEditDelete extends User implements Editable, Deletable{
public UserViewEditDelete() {
// TODO Auto-generated constructor stub
}
public UserViewEditDelete(int id, String username, String password,String role) {
super(id, username, password, role);
}
//delete message
@Override
public boolean deleteMessages(int id) {
try {
DatabaseManager.deleteMessage(id);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return false;
}
//update a message
@Override
public boolean editMessages(int id, String text) {
try {
DatabaseManager.updateMessage(id, text);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return false;
}
}
<file_sep>/README.md
# Mail-Platform
build a console application where you will be asked to read various inputs from the keyboard.
This application is not defined in terms of what it is but it is defined as to what it is expected to be doing in principal.
These inputs will be used as login details and as various actions to give the ability to the users of the system to interact with each other.
The interaction between the users is solely defined by you so you can decide,
•What kind of information you would like your users to interchange
•How often this information has or must be exchanged
•The role that each user has within the application
The output of the various subsystems will be displayed to the screen and it will be written to simple text files.
The following description of the logical units of the application is given to have a guideline to what it should be expected as minimum requirements.
A.Logical Units of the application
1.Main application
2.Login Screen
3.Application’s menus
4.Database’s access
5.Files’ access
|
751cd35e9387c6f7e820e5b7a7e193b99e4b6da3
|
[
"Markdown",
"Java"
] | 11
|
Java
|
vasgial/Mail-Platform
|
7bf94038a602ae590f56da42e6586cf668032d6a
|
bc74699c969e34f2a5c95841677eadcf17eb0472
|
refs/heads/master
|
<file_sep>process.env.NODE_ENV = 'test';
var assert = require("assert");
var Beer = require('../models/beer.js');
var indexController = require('../controllers/index.js');
var apiController = require('../controllers/api.js');
var app = require('../app.js');
var request = require('supertest')(app)
, express = require('express')
, mongoose = require('mongoose');
var bud = {
name: 'Budweiser',
ABV: 5.5,
type: 'pilsner or lager who knows',
brewer: 'Inbev'
};
var dummyBeer = {
name: '<NAME>',
ABV: 'eleven',
type: 'Lager',
brewer: 'Brewery'
};
describe('GET /', function(){
// beforeEach(function(done) {
// done()
// });
afterEach(function(done) {
Beer.remove({}, function(){
done();
});
});
// it('should fail if ABV not correct type', function(done){
// request
// .post('/api/addBeer')
// .send(dummyBeer)
// .expect(function(req){
// if(req.body.ABV !== Number(req.body.ABV)){
// throw new Error("ABV is not the correct data type");
// }
// })
// .expect(200, done);
// });
it('should pass when sent a beer', function(done){
request
.post('/api/addBeer')
.send(bud)
.expect(function(req){
if(req.body.ABV !== Number(req.body.ABV)){
throw new Error("ABV is not the correct data type");
}
})
.expect(function(req){
var key = req.body;
if(key.name.length === 0 || key.type.length === 0 || key.brewer.length === 0){
throw new Error("Data Missing from Object");
}
})
.expect(200, done);
});
it('should pass if 200 request is received', function(done){
request
.get('/')
.expect(/DOCTYPE/)
.expect('content-type', "text/html; charset=utf-8")
.expect(200, done);
});
});
describe('deleteBeer /', function(){
before(function(done){
budBeer = new Beer(bud);
budBeer.save();
done();
});
// after(function(done){
// Beer.remove({}, function(){
// done();
// });
// });
// THIS IS WHERE YOU WERE!!!
// Check to see if Beer.findById finds a beer with the same id as targetId
it('should pass if the targeted beer is deleted', function(done){
var targetId = budBeer.id;
var x = Beer.findById(targetId)
request
.post('/api/deleteBeer')
.send(budBeer)
.expect(function(req){
console.log(Beer)
})
.expect(200, done);
});
});
|
2ff2de094500f920d1143d296f9dec392a608ac0
|
[
"JavaScript"
] | 1
|
JavaScript
|
rb1econ/winter2015-demo-code
|
96b1b5f2608334056e731778167f36d96e407f31
|
fc5de517af93e085800b24cadb73610f4701b7eb
|
refs/heads/master
|
<file_sep><?php
/*
* Шаблон верхней части страницы админки
*
*/
?>
<!DOCTYPE html>
<html>
<head>
<base href="<?php echo $this->base; ?>" />
<title>Admin area</title>
<meta name="robots" content="all" />
<meta name="robots" content="index" />
<meta name="robots" content="follow" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="2 days" />
<meta name="rating" content="General" />
<meta name="distribution" content="GLOBAL" />
<meta name="author" content="http://www.freethenipple.biz" />
<meta name="copyright" content="http://www.freethenipple.biz" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="<?php echo $this->base; ?>/jquery.mobile-1.4.5/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="<?php echo $this->base; ?>/jquery.mobile-1.4.5/jqm.css">
<link rel="stylesheet" href="<?php echo $this->base; ?>/bootstrap/css/bootstrap.min.css">
<script src="<?php echo $this->base; ?>/jquery.mobile-1.4.5/jquery.js"></script>
<script src="<?php echo $this->base; ?>/jquery.mobile-1.4.5/index.js"></script>
<script src="<?php echo $this->base; ?>/jquery.mobile-1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="header" data-position="fixed">
<div data-role="navbar" data-position="fixed" data-theme="f">
<ul>
<li><a href="<?php echo $this->base; ?>/admin.php" class="ui-btn-active">Admin area</a></li>
<li><a href="<?php echo $this->base; ?>/admin/comments/" title="Free the nipple">Comments</a></li>
<li><a href="<?php echo $this->base; ?>/admin/news/">Edit news (<?php echo $newsCount; ?>)</a></li>
<li><a href="<?php echo $this->base; ?>/admin/add/">Add news</a></li>
</ul>
</div>
</div>
<div>
<div style="width: 100%; max-width: 1100px; margin: 0 auto;">
<div role="main" class="ui-content">
<file_sep><form action="<?php echo $this->base; ?>/admin/edit/<?php echo $id; ?>" method="post" data-ajax="false">
<div class="panel panel-default">
<div class="panel-heading" align="left">Title:
<input type="text" value="<?php echo $key['Title']; ?>" name="edit[title]">
Description:
<input type="text" value="<?php echo $key['Description']; ?>" name="edit[description]">
Keyword:
<input type="text" value="<?php echo $key['Keyword']; ?>" name="edit[keyword]">
URL:
<input type="text" value="<?php echo $key['URL']; ?>" name="edit[url]">
</div>
<div class="panel-body" align="left">Small text:
<textarea name="edit[small]"><?php echo $key['Small text']; ?></textarea>
Main text:
<textarea name="edit[main]"><?php echo $key['Main text']; ?></textarea>
Vote question:
<input type="text" value="<?php echo $key['Vote question']; ?>" name="edit[vote]">
</div>
<div class="panel-footer" align="left">
<input type="submit" value="Save">
</div>
</div>
<input type="hidden" name="edit[news]" value="<?php echo $key['id']; ?>">
</form><file_sep><div class="panel panel-default">
<div class="panel-heading" align="left"><?php echo $key['Title']; ?></div>
<div class="panel-body" align="left">
<?php echo $key['Small text']; ?>
<div align="right">
<a class="jqm-view-source-link ui-btn ui-corner-all
ui-btn-inline ui-mini" href="<?php echo $this->base; ?>/admin/edit/<?php echo $key['id']; ?>" data-ajax="false">Edit</a>
</div>
</div>
<div class="panel-footer" align="left">
Comments: <?php echo $comments; ?>
</div>
</div><file_sep><?php
class image {
function twoImage($view, $data)
{
$date = $data['date'];
$ip = $data['ip'];
$functionComment = $data['functionComment'];
$functionGetLastId = $data['functionGetLastId'];
$extension1 = explode(".", $_FILES['photo1']['name']);
$extension2 = explode(".", $_FILES['photo2']['name']);
$uploadfile = md5(rand() . $_FILES['photo1']['name']) . '.' . $extension1[1];
$uploadfile2 = md5(rand() . $_FILES['photo2']['name']) . '.' . $extension2[1];
if (move_uploaded_file($_FILES["photo1"]['tmp_name'], $uploadfile) &&
move_uploaded_file($_FILES["photo2"]['tmp_name'], $uploadfile2))
{
$name = filter_var($_POST['comment']['name'], FILTER_SANITIZE_STRING);
$comment = filter_var($_POST['comment']['content'], FILTER_SANITIZE_STRING);
// Images:
$ext = array(IMAGETYPE_GIF, IMAGETYPE_JPEG);
$a = getimagesize($uploadfile);
$b = getimagesize($uploadfile2);
if (!$a || !$b)
{
die();
}
if (in_array($a[2], $ext) && in_array($b[2], $ext))
{
echo $view->$functionComment($date, $name, $comment, 1, $ip);
// Convert
exec('ffmpeg -i ' . $uploadfile . ' -pix_fmt rgb24 -vf "scale=-1:500" ./img/' . $view->$functionGetLastId() . '_1.gif');
unlink($uploadfile);
exec('ffmpeg -i ' . $uploadfile2 . ' -pix_fmt rgb24 -vf "scale=-1:500" ./img/' . $view->$functionGetLastId() . '_2.gif');
unlink($uploadfile2);
}
else
{
@unlink($uploadfile);
@unlink($uploadfile2);
}
}
}
function aImage($view, $data)
{
$date = $data['date'];
$ip = $data['ip'];
$functionComment = $data['functionComment'];
$functionGetLastId = $data['functionGetLastId'];
$extension1 = explode(".", $_FILES['photo1']['name']);
$uploadfile = md5(rand() . $_FILES['photo1']['name']) . '.' . $extension1[1];
if (move_uploaded_file($_FILES["photo1"]['tmp_name'], $uploadfile))
{
$name = filter_var($_POST['comment']['name'], FILTER_SANITIZE_STRING);
$comment = filter_var($_POST['comment']['content'], FILTER_SANITIZE_STRING);
// Images:
$ext = array(IMAGETYPE_GIF, IMAGETYPE_JPEG);
$a = getimagesize($uploadfile);
if (!$a)
{
die();
}
if (in_array($a[2], $ext))
{
echo $view->$functionComment($date, $name, $comment, 1, $ip);
// Convert
exec('ffmpeg -i ' . $uploadfile . ' -pix_fmt rgb24 -vf "scale=-1:500" ./img/' . $view->$functionGetLastId() . '_1.gif');
unlink($uploadfile);
}
else
{
@unlink($uploadfile);
}
}
}
function bImage($view, $data)
{
$date = $data['date'];
$ip = $data['ip'];
$functionComment = $data['functionComment'];
$functionGetLastId = $data['functionGetLastId'];
$extension2 = explode(".", $_FILES['photo2']['name']);
$uploadfile2 = md5(rand() . $_FILES['photo2']['name']) . '.' . $extension2[1];
if (move_uploaded_file($_FILES["photo2"]['tmp_name'], $uploadfile2))
{
$name = filter_var($_POST['comment']['name'], FILTER_SANITIZE_STRING);
$comment = filter_var($_POST['comment']['content'], FILTER_SANITIZE_STRING);
// Images:
$ext = array(IMAGETYPE_GIF, IMAGETYPE_JPEG);
$b = getimagesize($uploadfile2);
if (!$b)
{
die();
}
if (in_array($b[2], $ext))
{
echo $view->$functionComment($date, $name, $comment, 1, $ip);
// Convert
exec('ffmpeg -i ' . $uploadfile2 . ' -pix_fmt rgb24 -vf "scale=-1:500" ./img/' . $view->$functionGetLastId() . '_2.gif');
unlink($uploadfile2);
}
else
{
@unlink($uploadfile2);
}
}
}
}
<file_sep><?php
/*
* Шаблон верхней части страницы.
*
* $newsCount -- задаётся в index.php и выводит общее количество новостей.
*/
?>
<!DOCTYPE html>
<html>
<head>
<base href="<?php echo $this->base; ?>" />
<title><?php echo $title; ?></title>
<meta name="keywords" content="<?php echo $keywords; ?>" />
<meta name="description" content="<?php echo $description; ?>" />
<meta name="robots" content="all" />
<meta name="robots" content="index" />
<meta name="robots" content="follow" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="2 days" />
<meta name="rating" content="General" />
<meta name="distribution" content="GLOBAL" />
<meta name="author" content="http://www.freethenipple.biz" />
<meta name="copyright" content="http://www.freethenipple.biz" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="<?php echo $this->base; ?>/jquery.mobile-1.4.5/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="<?php echo $this->base; ?>/jquery.mobile-1.4.5/jqm.css">
<link rel="stylesheet" href="<?php echo $this->base; ?>/bootstrap/css/bootstrap.min.css">
<script src="<?php echo $this->base; ?>/jquery.mobile-1.4.5/jquery.js"></script>
<script src="<?php echo $this->base; ?>/jquery.mobile-1.4.5//index.js"></script>
<script src="<?php echo $this->base; ?>/jquery.mobile-1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="header" data-position="fixed">
<div data-role="navbar" data-position="fixed" data-theme="f">
<ul>
<?php
foreach ($links as $title => $attr)
{
?>
<li><a href="<?php echo $this->base; ?>/<?php echo $attr['url']; ?>" class="<?php echo $attr['class']; ?>" title="<?php echo $title; ?>"><?php echo $title; ?></a></li>
<?php
}
?>
<li><a class="ui-link ui-btn" target="_blank" href="https://secure.verotel.com/order/purchase?description=Free+the+nipple&paymentMethod=CC&priceAmount=10&priceCurrency=USD&shopID=104450&version=2&signature=cee59ee55f792641feb8f99154353af98e40f80e">Membership</a></li>
</ul>
</div>
</div>
<div>
<div style="width: 100%; max-width: 1100px; margin: 0 auto;">
<div role="main" class="ui-content">
<file_sep><?php
/*
* Вывод постраничного анонса новостей
*
*/
error_reporting(E_ALL);
date_default_timezone_set('UTC');
// Мета-теги для страницы:
$title = 'Free the nipple | Stop censorship!';
$keywords = 'free the nipple, #freethenipple, stop censorship, naked, woman, boobs, tits';
$description = 'Why we can look at the scenes of violence and cruelty, and can not look at a naked woman?';
require_once 'class.Sql.php';
require_once 'class.Render.php';
$view = new Sql();
$render = new Render();
$newsCount = $view->newsCounter();
// Ссылки:
$links = array(
'Free the nipple' => array(
'url' => 'index.php',
'class' => '',
),
'Add comment' => array(
'url' => 'add/',
'class' => '',
),
'Related news (' . $newsCount . ')' => array(
'url' => 'announce/',
'class' => 'ui-btn-active',
),
'Subscribe' => array(
'url' => 'subscribe/',
'class' => '',
),
);
/* Подсчёт количества новостей и вывод в шапку */
$render->header($newsCount, $title, $description, $keywords, $links);
// Количество страниц анонсов новостей, передаём в пагинацию
$pages = $view->numNews();
$render->announcePagination($view, $pages);
if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0)
$id = $_GET['page'];
else
$id = 1;
// Вывод блока новостей:
if ($view->selectNews($id))
foreach ($view->selectNews($id) as $key)
{
$comments = $view->announceCommentCounter($key['URL']);
$render->announceBlock($key, $comments);
}
else
$render->notFoundError();
$render->announcePagination($view, $pages);
<file_sep><div class="panel panel-default">
<div class="panel-heading">Comment form</div>
<div class="panel-body">
<div role="main" class="ui-content">
<form enctype="multipart/form-data" action="<?php echo $this->base; ?>/news/<?php echo $url; ?>/" method="post" data-ajax="false">
<input type="hidden" name="comment[type]" value="1">
<input type="hidden" name="MAX_FILE_SIZE" value="3000000">
<input name="photo1" type="file" accept="image/*">
<input name="photo2" type="file" accept="image/*">
<input type="text" class="form-control" placeholder="Your name" name="comment[name]" required="">
<input type="text" class="form-control" placeholder="Your comment" name="comment[content]" required="">
<button type="submit" class="btn btn-success">Send</button>
</form>
</div>
</div>
</div><file_sep><?php
/*
*
* Шаблон вывода отдельной новости
*
*/
?>
<div class="panel panel-default">
<div class="panel-heading" align="left">
<?php echo $key['Title']; ?>
</div>
<div class="panel-body" align="left">
<?php echo nl2br($key['Main text']); ?>
</div>
<div class="panel-footer" align="left">
<?php echo $key['Keyword']; ?>
</div>
</div>
<file_sep>freethenipple
=============
<file_sep><?php
error_reporting(E_ALL);
date_default_timezone_set('UTC');
// Мета-теги для страницы:
$title = 'Free the nipple | Stop censorship!';
$keywords = 'free the nipple, #freethenipple, stop censorship, naked, woman, boobs, tits';
$description = 'Why we can look at the scenes of violence and cruelty, and can not look at a naked woman?';
// Подключаем классы
require_once 'class.Sql.php';
require_once 'class.Render.php';
$view = new Sql();
$render = new Render();
$pages = $view->numPages();
$newsCount = $view->newsCounter();
$status = $view->status();
// Ссылки:
$links = array(
'Edit comments' => array(
'url' => 'admin.php',
'class' => '',
),
'Edit news (' . $newsCount . ')' => array(
'url' => 'admin/news/',
'class' => '',
),
'Add news' => array(
'url' => 'admin/add/',
'class' => '',
),
);
if (isset($_GET['action']))
{
switch ($_GET['action'])
{
// Удаление поста по id:
case "delete":
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$id = $_GET['id'];
// Удаляем запись из БД
$view->delete($id);
// Удаляем фотку №1
if (file_exists('./img/' . $id . '_1.gif'))
@unlink('./img/' . $id . '_1.gif');
// Удаляем фотку №2
if (file_exists('./img/' . $id . '_2.gif'))
@unlink('./img/' . $id . '_2.gif');
unset($id);
header("location: ./admin.php");
die;
}
break;
case "ban":
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$id = $_GET['id'];
// Удаляем запись из БД
$view->delete($id);
$ipAddress = $_SERVER['REMOTE_ADDR'];
$view->ban($ipAddress);
// Удаляем фотку №1
if (file_exists('./img/' . $id . '_1.gif'))
@unlink('./img/' . $id . '_1.gif');
// Удаляем фотку №2
if (file_exists('./img/' . $id . '_2.gif'))
@unlink('./img/' . $id . '_2.gif');
unset($id);
header("location: ./admin.php");
die;
}
break;
case "approve":
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$id = $_GET['id'];
$view->approve($id);
header("location: ./admin.php");
die;
}
break;
// Обработчик формы входа
case "login":
if (isset($_POST['admin']['name']) && isset($_POST['admin']['password']))
{
$name = filter_var($_POST['admin']['name'], FILTER_SANITIZE_STRING);
$pass = filter_var($_POST['admin']['password'], FILTER_SANITIZE_STRING);
if ($view->checkPassword($name) == $pass)
{
$view->startSession($name);
header("location: ./admin.php");
die;
}
else
{
header("location: ./admin.php");
die;
}
}
break;
// Вывод списка новостей для редактирования
case "news":
if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0)
$id = $_GET['page'];
else
$id = 1;
$newsCount = $view->newsCounter();
$render->header($newsCount, $title, $description, $keywords, $links);
$render->adminNewsPagination($view, $view->numNews());
foreach ($view->selectNews($id) as $key)
$render->adminNewsBlock($key);
$render->adminNewsPagination($view, $view->numNews());
break;
// Редактирование новости по id:
case "edit":
// Сохраняем новость:
if (isset($_POST["edit"]["news"]) && is_numeric($_POST["edit"]["news"]))
{
echo $view->updateNewsText($_POST["edit"]["title"], $_POST["edit"]["description"], $_POST["edit"]["keyword"], $_POST["edit"]["url"], $_POST["edit"]["small"], $_POST["edit"]["main"], $_POST["edit"]["vote"], $_POST["edit"]["news"]);
}
// Аппрувим комментатора
if (isset($_POST["edit"]["approve"]) && is_numeric($_POST["edit"]["approve"]))
$view->newsCommentApprove($_POST["edit"]["approve"]);
// Баним комментатора и удаляем коммент
if (isset($_POST["edit"]["ban"]) && isset($_POST["edit"]["bandelete"]))
{
$ip = $view->checkBan($_POST["edit"]["ban"]);
if ($ip != 0)
$view->ban($_POST["edit"]["ban"]);
$view->newsCommentDelete($_POST["edit"]["bandelete"]);
}
// Удаляем коммент
if (isset($_POST["edit"]["delete"]) && is_numeric($_POST["edit"]["delete"]))
$view->newsCommentDelete($_POST["edit"]["delete"]);
// Редактируем новость
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$id = $_GET['page'];
$url = $view->getNewsUrlById($id);
$key = $view->printArticleById($id);
$newsCount = $view->newsCounter();
$render->header($newsCount, $title, $description, $keywords, $links);
$render->adminNewsEdit($key, $id);
// Вывод комментариев
if ($view->newsComments(0, $url['URL']))
{
foreach ($view->newsComments(0, $url['URL']) as $key)
{
$render->adminNewsComment(0, $key, $status);
}
}
}
break;
// Добавляем новость
case "add":
if (isset($_POST['edit']))
{
$datetime = new DateTime();
$date = $datetime->getTimestamp();
$view->addNewsText($_POST["edit"]["title"], $_POST["edit"]["description"], $_POST["edit"]["keyword"], $_POST["edit"]["url"], $_POST["edit"]["small"], $_POST["edit"]["main"], $_POST["edit"]["vote"], $date);
header("Location: ../news/");
}
$newsCount = $view->newsCounter();
$render->header($newsCount, $title, $description, $keywords, $links);
$render->adminNewsAdd();
break;
}
}
else
{
// Вывод комментариев:
if ($view->checkSession())
{
// Вывод шапки:
$render->header($newsCount, $title, $description, $keywords, $links);
if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0)
$id = $_GET['page'];
else
$id = 1;
$render->adminPagination($view, $pages);
// Постраничный показ:
foreach ($view->select($id) as $key)
$render->commentBlockAdmin($key, $status);
$render->adminPagination($view, $pages);
// Вывод подвала страницы:
$render->footer();
}
else
{
print_r($view->checkSession());
$render->form();
}
}
?><file_sep><?php
error_reporting(E_ALL);
date_default_timezone_set('UTC');
// Мета-теги для страницы:
$title = 'Add yourself | Stop censorship! | Image Upload';
$keywords = 'free the nipple, #freethenipple, stop censorship, naked, woman, boobs, tits';
$description = 'Why we can look at the scenes of violence and cruelty, and can not look at a naked woman?';
// Подключаем классы
require_once 'class.Sql.php';
require_once 'class.Render.php';
$view = new Sql();
$render = new Render();
$pages = $view->numPages();
$newsCount = $view->newsCounter();
// Ссылки:
$links = array(
'Free the nipple' => array(
'url' => 'index.php',
'class' => '',
),
'Add comment' => array(
'url' => 'add/',
'class' => 'ui-btn-active',
),
'Related news (' . $newsCount . ')' => array(
'url' => 'announce/',
'class' => '',
),
'Subscribe' => array(
'url' => 'index.php/#subscribe',
'class' => '',
),
);
// Обработчик добавления комментариев
$datetime = new DateTime();
$date = $datetime->getTimestamp();
$ip = $_SERVER['REMOTE_ADDR'];
// Если ip не в бане
if ($view->checkBan($ip) == 0)
{
// Если заполнены поля комментарий и имя и два изображения:
if (!empty($_POST['comment']['name']) && !empty($_POST['comment']['content']) &&
!empty($_FILES['photo1']['name']) && !empty($_FILES['photo2']['name']))
{
require_once 'class.Image.php';
$image = new image();
$data = array(
'date' => $date,
'ip' => $ip,
'functionComment' => 'addComment',
'functionGetLastId' => 'getLastCommentId',
);
$image->twoImage($view, $data);
header("location: ../");
die;
}
elseif (!empty($_POST['comment']['name']) && !empty($_POST['comment']['content']) &&
!empty($_FILES['photo1']['name']))
{
require_once 'class.Image.php';
$image = new image();
$data = array(
'date' => $date,
'ip' => $ip,
'functionComment' => 'addComment',
'functionGetLastId' => 'getLastCommentId',
);
$image->aImage($view, $data);
header("location: ../");
die;
}
elseif (!empty($_POST['comment']['name']) && !empty($_POST['comment']['content']) &&
!empty($_FILES['photo2']['name']))
{
require_once 'class.Image.php';
$image = new image();
$data = array(
'date' => $date,
'ip' => $ip,
'functionComment' => 'addComment',
'functionGetLastId' => 'getLastCommentId',
);
$image->bImage($view, $data);
header("location: ../");
die;
}
// Действие, если комментарий без картинок
elseif (!empty($_POST['comment']['name']) && !empty($_POST['comment']['content']))
{
$name = filter_var($_POST['comment']['name'], FILTER_SANITIZE_STRING);
$comment = filter_var($_POST['comment']['content'], FILTER_SANITIZE_STRING);
echo $view->addComment($date, $name, $comment, 2, $ip);
header("location: ../");
die;
}
}
// Вывод верхней части страницы:
$render->header($newsCount, $title, $description, $keywords, $links);
$render->body('add');
$render->footer();
?><file_sep><?php
/*
* Шаблон верхней части страницы.
*
* $newsCount -- задаётся в index.php и выводит общее количество новостей.
*/
$base = "http://rvs.pp.ua/www.freethenipple.biz";
?>
<!DOCTYPE html>
<html>
<head>
<base href="<?php echo $base; ?>" />
<title><?php echo $key['Title']; ?> | <?php echo $key['Description']; ?></title>
<meta name="keywords" content="<?php echo $key['Keyword']; ?>" />
<meta name="description" content="<?php echo $key['Description']; ?>" />
<meta name="robots" content="all" />
<meta name="robots" content="index" />
<meta name="robots" content="follow" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="2 days" />
<meta name="rating" content="General" />
<meta name="distribution" content="GLOBAL" />
<meta name="author" content="http://www.freethenipple.biz" />
<meta name="copyright" content="http://www.freethenipple.biz" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="<?php echo $base; ?>/jquery.mobile-1.4.5/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="<?php echo $base; ?>/jquery.mobile-1.4.5/jqm.css">
<link rel="stylesheet" href="<?php echo $base; ?>/bootstrap/css/bootstrap.min.css">
<script src="<?php echo $base; ?>/jquery.mobile-1.4.5/jquery.js"></script>
<script src="<?php echo $base; ?>/jquery.mobile-1.4.5//index.js"></script>
<script src="<?php echo $base; ?>/jquery.mobile-1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="header" data-position="fixed">
<div data-role="navbar" data-position="fixed" data-theme="f">
<ul>
<li><a href="<?php echo $base; ?>/index.php" class="ui-btn-active" title="Free the nipple">Free the nipple</a></li>
<li><a href="<?php echo $base; ?>/index.php/#comment">Add comment</a></li>
<li><a href="<?php echo $base; ?>/index.php/#news">Related news (<?php echo $newsCount; ?>)</a></li>
<li><a href="<?php echo $base; ?>/index.php/#subscribe">Subscribe</a></li>
</ul>
</div>
</div>
<div>
<div style="width: 100%; max-width: 1100px; margin: 0 auto;">
<div role="main" class="ui-content">
<file_sep><form action="<?php echo $this->base; ?>/admin/add/" method="post" data-ajax="false">
<div class="panel panel-default">
<div class="panel-heading" align="left">Title:
<input type="text" value="" name="edit[title]">
Description:
<input type="text" value="" name="edit[description]">
Keyword:
<input type="text" value="" name="edit[keyword]">
URL:
<input type="text" value="" name="edit[url]">
</div>
<div class="panel-body" align="left">Small text:
<textarea name="edit[small]"></textarea>
Main text:
<textarea name="edit[main]"></textarea>
Vote question:
<input type="text" value="" name="edit[vote]">
</div>
<div class="panel-footer" align="left">
<input type="submit" value="Save">
</div>
</div>
</form><file_sep><div class="panel panel-default">
<div class="panel-heading"><?php echo $key['name']; ?>: <?php echo date("d/m/Y H:i:s", $key['date']); ?></div>
<div class="panel-body" align="center">
<div align="left">
<?php echo $key['comment']; ?>
</div>
</div>
</div><file_sep><?php
error_reporting(E_ALL);
date_default_timezone_set('UTC');
// Мета-теги для страницы:
$title = 'Free the nipple | Stop censorship!';
$keywords = 'free the nipple, #freethenipple, stop censorship, naked, woman, boobs, tits';
$description = 'Why we can look at the scenes of violence and cruelty, and can not look at a naked woman?';
// Подключаем классы
require_once 'class.Sql.php';
require_once 'class.Render.php';
$view = new Sql();
$render = new Render();
$pages = $view->numPages();
$newsCount = $view->newsCounter();
// Ссылки:
$links = array(
'Free the nipple' => array(
'url' => 'index.php',
'class' => 'ui-btn-active',
),
'Add comment' => array(
'url' => 'add/',
'class' => '',
),
'Related news (' . $newsCount . ')' => array(
'url' => 'announce/',
'class' => '',
),
'Subscribe' => array(
'url' => 'subscribe/',
'class' => '',
),
);
$ip = $_SERVER['REMOTE_ADDR'];
if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0)
$id = $_GET['page'];
else
$id = 1;
// Обработчик голосования
if (isset($_POST['vote']))
{
// Проверяем, голосовал ли этот Ip:
$vote = "vote_1";
$result = $view->checkVoteIp($vote, $ip);
if ($result == 0)
{
switch ($_POST['vote'])
{
case 'Yes':
$view->vote($vote, '1', $ip);
break;
case 'No':
$view->vote($vote, '1', $ip);
break;
}
}
}
// Вывод верхней части страницы:
$render->header($newsCount, $title, $description, $keywords, $links);
$render->indexPagination($view, $pages);
// Вывод front.block.php
if (!isset($_GET['page']) && $_SERVER["REQUEST_URI"] != '/index.php')
{
$render->front('index');
$vote = "vote_1";
$result = $view->checkVoteIp($vote, $ip);
// Вывод результатов голосования:
$voteResult = $view->voteCounter($vote);
if ($voteResult['yes'] + $voteResult['no'] != 0)
{
$all = 100 / ($voteResult['yes'] + $voteResult['no']);
$yes = round($voteResult['yes'] * $all, 1);
$no = round($voteResult['no'] * $all, 1);
}
else
{
$yes = 100;
$no = 100;
$voteResult['yes'] = 0;
$voteResult['no'] = 0;
}
if ($result == 0)
$render->unvoted("index", $voteResult, $yes, $no);
else
$render->voted("index", $voteResult, $yes, $no);
}
if ($view->select($id))
foreach ($view->select($id) as $key)
$render->imageBlock("index", $key);
else
$render->notFoundError();
// Вывод пагинации
$render->indexPagination($view, $pages);
require_once './tpl/social.links.php';
require_once './tpl/footer.php';
?>
<file_sep><div class="panel panel-default">
<div class="panel-heading"><?php echo $key['name']; ?>: <?php echo date("d/m/Y H:i:s", $key['date']); ?></div>
<div class="panel-body" align="center">
<?php
if ($key['type'] == 1)
{
?>
<div class="row-fluid">
<div class="col-md-12"><img style="height: 100%; max-width: 500px; width: 100%; display: inline;" src="<?php echo $this->base; ?>/img/<?php echo $key['id']; ?>_2.gif" class="img-rounded img-responsive thumbnail"></div>
</div>
</div>
<div class="panel-footer">
<?php } ?>
<?php echo $key['comment']; ?>
<?php
if ($status == 1 && $key['status'] == 0)
{
?>
<button onclick="window.location.href = '<?php echo $this->base; ?>/admin.php?action=approve&id=<?php echo $key['id']; ?>'">Approve</button>
<?php } ?>
<button onclick="window.location.href = '<?php echo $this->base; ?>/admin.php?action=ban&id=<?php echo $key['id']; ?>'">Ban</button>
<button onclick="window.location.href = '<?php echo $this->base; ?>/admin.php?action=delete&id=<?php echo $key['id']; ?>'">Delete</button>
</div>
</div>
</div><file_sep><?php
class Render {
public $base = "http://freethenipple.rvs.pp.ua";
function header($newsCount, $title, $description, $keywords, $links)
{
require_once './tpl/header.php';
}
// Выводим тело главнйо страницы:
function body($page)
{
require_once './tpl/' . $page . '/body.php';
}
function front($page)
{
require_once './tpl/' . $page . '/front.php';
}
function voted($page, $voteResult, $yes, $no)
{
require_once './tpl/' . $page . '/voted.php';
}
function unvoted($page, $voteResult, $yes, $no)
{
require_once './tpl/' . $page . '/unvoted.php';
}
function imageBlock($page, $key)
{
if (file_exists('./img/' . $key['id'] . '_1.gif') &&
file_exists('./img/' . $key['id'] . '_2.gif'))
{
include './tpl/' . $page . '/twoimg.comment.php';
}
elseif (file_exists('./img/' . $key['id'] . '_1.gif'))
{
include './tpl/' . $page . '/1img.comment.php';
}
elseif (file_exists('./img/' . $key['id'] . '_2.gif'))
{
include './tpl/' . $page . '/2img.comment.php';
}
else
{
include './tpl/' . $page . '/single.post.php';
}
}
function imageBlockAdmin($page, $key, $status)
{
if (file_exists('./img/' . $key['id'] . '_1.gif') &&
file_exists('./img/' . $key['id'] . '_2.gif'))
{
include './tpl/' . $page . '/twoimg.comment.php';
}
elseif (file_exists('./img/' . $key['id'] . '_1.gif'))
{
include './tpl/' . $page . '/1img.comment.php';
}
elseif (file_exists('./img/' . $key['id'] . '_2.gif'))
{
include './tpl/' . $page . '/2img.comment.php';
}
else
{
include './tpl/' . $page . '/single.post.php';
}
}
function adminHeader($newsCount)
{
require_once './tpl/admin/header.php';
}
function adminNewsBlock($key, $comments)
{
include './tpl/admin/news.block.php';
}
function adminNewsEdit($key, $id)
{
include './tpl/admin/news.edit.php';
}
function commentForm($page, $url)
{
include './tpl/' . $page . '/form.php';
}
function adminNewsComment($id, $key, $status)
{
$page = "admin";
if (file_exists('./img/' . $key['id'] . '_1.gif') &&
file_exists('./img/' . $key['id'] . '_2.gif'))
{
include './tpl/' . $page . '/twoimg.comment.php';
}
elseif (file_exists('./img/' . $key['id'] . '_1.gif'))
{
include './tpl/' . $page . '/1img.comment.php';
}
elseif (file_exists('./img/' . $key['id'] . '_2.gif'))
{
include './tpl/' . $page . '/2img.comment.php';
}
else
{
include './tpl/' . $page . '/single.post.php';
}
}
function commentBlockAdmin($id, $key, $status)
{
$page = "admin";
if (file_exists('./img/' . $key['id'] . '_1.gif') &&
file_exists('./img/' . $key['id'] . '_2.gif'))
include './tpl/' . $page . '/twoimg.ccomment.php';
elseif (file_exists('./img/' . $key['id'] . '_1.gif'))
include './tpl/' . $page . '/1img.ccomment.php';
elseif (file_exists('./img/' . $key['id'] . '_2.gif'))
include './tpl/' . $page . '/2img.ccomment.php';
else
include './tpl/' . $page . '/single.cpost.php';
}
// Добавление новости
function adminNewsAdd()
{
include './tpl/admin/news.add.php';
}
function adminNewsPagination($sql, $pages)
{
if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0)
$id = $_GET['page'];
else
$id = 1;
if ($pages == 1)
{
$class_prev = 'disabled';
$class_next = 'disabled';
$previous = $pages;
$next = $pages;
}
else
{
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$previous = $_GET['page'] - 1;
if (($_GET['page'] - 1) < 1)
{
$previous = 1;
$class_prev = 'disabled';
}
else
{
$previous = $_GET['page'] - 1;
}
if (($_GET['page'] + 1) <= $pages)
{
$next = $_GET['page'] + 1;
}
else
{
$class_next = 'disabled';
$next = $pages;
}
}
else
{
$class_prev = 'disabled';
$previous = 1;
$next = 2;
}
}
if (!isset($class_next))
$class_next = null;
if (!isset($class_prev))
$class_prev = null;
?>
<div class="text-center">
<nav>
<ul class="pagination">
<li class="<?php echo $class_prev; ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/admin/news/<?php echo $previous; ?>">
<span aria-hidden="true">«</span><span class="sr-only">Previous</span>
</a>
</li>
<?php
$i = 0;
while ($i != $pages)
{
$i++;
?>
<li class="<?php echo $sql->activePage($id, $i); ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/admin/news/<?php echo $i; ?>"><?php echo $i; ?></a>
</li>
<?php
}
?>
<li class="<?php echo $class_next; ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/admin/news/<?php echo $next; ?>">
<span aria-hidden="true">»</span><span class="sr-only">Next</span>
</a>
</li>
</ul>
</nav>
</div>
<?php
}
function adminPagination($sql, $pages)
{
if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0)
$id = $_GET['page'];
else
$id = 1;
if ($pages == 1)
{
$class_prev = 'disabled';
$class_next = 'disabled';
$previous = $pages;
$next = $pages;
}
else
{
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$previous = $_GET['page'] - 1;
if (($_GET['page'] - 1) < 1)
{
$previous = 1;
$class_prev = 'disabled';
}
else
{
$previous = $_GET['page'] - 1;
}
if (($_GET['page'] + 1) <= $pages)
{
$next = $_GET['page'] + 1;
}
else
{
$class_next = 'disabled';
$next = $pages;
}
}
else
{
$class_prev = 'disabled';
$previous = 1;
$next = 2;
}
}
if (!isset($class_next))
$class_next = null;
if (!isset($class_prev))
$class_prev = null;
?>
<div class="text-center">
<nav>
<ul class="pagination">
<li class="<?php echo $class_prev; ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/admin.php?page=<?php echo $previous; ?>">
<span aria-hidden="true">«</span><span class="sr-only">Previous</span>
</a>
</li>
<?php
$i = 0;
while ($i != $pages)
{
$i++;
?>
<li class="<?php echo $sql->activePage($id, $i); ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/admin.php?page=<?php echo $i; ?>"><?php echo $i; ?></a>
</li>
<?php
}
?>
<li class="<?php echo $class_next; ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/admin.php?page=<?php echo $next; ?>">
<span aria-hidden="true">»</span><span class="sr-only">Next</span>
</a>
</li>
</ul>
</nav>
</div>
<?php
}
function newsPagination($sql, $pages, $url)
{
if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0)
$id = $_GET['page'];
else
$id = 1;
if ($pages == 1)
{
$class_prev = 'disabled';
$class_next = 'disabled';
$previous = $pages;
$next = $pages;
}
else
{
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$previous = $_GET['page'] - 1;
if (($_GET['page'] - 1) < 1)
{
$previous = 1;
$class_prev = 'disabled';
}
else
{
$previous = $_GET['page'] - 1;
}
if (($_GET['page'] + 1) <= $pages)
{
$next = $_GET['page'] + 1;
}
else
{
$class_next = 'disabled';
$next = $pages;
}
}
else
{
$class_prev = 'disabled';
$previous = 1;
$next = 2;
}
}
if (!isset($class_next))
$class_next = null;
if (!isset($class_prev))
$class_prev = null;
?>
<div class="text-center">
<nav>
<ul class="pagination">
<li class="<?php echo $class_prev; ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/news/<?php echo $url; ?>/<?php echo $previous; ?>">
<span aria-hidden="true">«</span><span class="sr-only">Previous</span>
</a>
</li>
<?php
$i = 0;
while ($i != $pages)
{
$i++;
?>
<li class="<?php echo $sql->activePage($id, $i); ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/news/<?php echo $url; ?>/<?php echo $i; ?>"><?php echo $i; ?></a>
</li>
<?php
}
?>
<li class="<?php echo $class_next; ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/news/<?php echo $url; ?>/<?php echo $next; ?>">
<span aria-hidden="true">»</span><span class="sr-only">Next</span>
</a>
</li>
</ul>
</nav>
</div>
<?php
}
function announcePagination($sql, $pages)
{
if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0)
$id = $_GET['page'];
else
$id = 1;
if ($pages == 1)
{
$class_prev = 'disabled';
$class_next = 'disabled';
$previous = $pages;
$next = $pages;
}
else
{
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$previous = $_GET['page'] - 1;
if (($_GET['page'] - 1) < 1)
{
$previous = 1;
$class_prev = 'disabled';
}
else
{
$previous = $_GET['page'] - 1;
}
if (($_GET['page'] + 1) <= $pages)
{
$next = $_GET['page'] + 1;
}
else
{
$class_next = 'disabled';
$next = $pages;
}
}
else
{
$class_prev = 'disabled';
$previous = 1;
$next = 2;
}
}
if (!isset($class_next))
$class_next = null;
if (!isset($class_prev))
$class_prev = null;
?>
<div class="text-center">
<nav>
<ul class="pagination">
<li class="<?php echo $class_prev; ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/announce/<?php echo $previous; ?>">
<span aria-hidden="true">«</span><span class="sr-only">Previous</span>
</a>
</li>
<?php
$i = 0;
while ($i != $pages)
{
$i++;
?>
<li class="<?php echo $sql->activePage($id, $i); ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/announce/<?php echo $i; ?>"><?php echo $i; ?></a>
</li>
<?php
}
?>
<li class="<?php echo $class_next; ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/announce/<?php echo $next; ?>">
<span aria-hidden="true">»</span><span class="sr-only">Next</span>
</a>
</li>
</ul>
</nav>
</div>
<?php
}
function indexPagination($sql, $pages)
{
if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0)
$id = $_GET['page'];
else
$id = 1;
if ($pages == 1)
{
$class_prev = 'disabled';
$class_next = 'disabled';
$previous = $pages;
$next = $pages;
}
else
{
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$previous = $_GET['page'] - 1;
if (($_GET['page'] - 1) < 1)
{
$previous = 1;
$class_prev = 'disabled';
}
else
{
$previous = $_GET['page'] - 1;
}
if (($_GET['page'] + 1) <= $pages)
{
$next = $_GET['page'] + 1;
}
else
{
$class_next = 'disabled';
$next = $pages;
}
}
else
{
$class_prev = 'disabled';
$previous = 1;
$next = 2;
}
}
if (!isset($class_next))
$class_next = null;
if (!isset($class_prev))
$class_prev = null;
?>
<div class="text-center">
<nav>
<ul class="pagination">
<li class="<?php echo $class_prev; ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/page/<?php echo $previous; ?>">
<span aria-hidden="true">«</span><span class="sr-only">Previous</span>
</a>
</li>
<?php
$i = 0;
while ($i != $pages)
{
$i++;
?>
<li class="<?php echo $sql->activePage($id, $i); ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/page/<?php echo $i; ?>"><?php echo $i; ?></a>
</li>
<?php
}
?>
<li class="<?php echo $class_next; ?>">
<a class="ui-link-inherit" data-ajax="false" href="<?php echo $this->base; ?>/page/<?php echo $next; ?>">
<span aria-hidden="true">»</span><span class="sr-only">Next</span>
</a>
</li>
</ul>
</nav>
</div>
<?php
}
function footer()
{
require_once './tpl/footer.php';
}
function form()
{
require_once './tpl/adm.login.php';
}
// Вывод блока анонса новостей:
function announceBlock($key, $comments)
{
include './tpl/announce/announce.block.php';
}
function notFoundError()
{
require_once './tpl/errors/page.not.found.php';
}
function subscribePage()
{
require_once './tpl/block/subscribe.block.php';
}
function uploadPage()
{
require_once './tpl/block/upload.block.php';
}
function commentPage()
{
require_once './tpl/block/comment.block.php';
}
function preblock()
{
require_once './tpl/block/pre.block.php';
}
function block($id, $content)
{
require_once './tpl/system/block.php';
}
}
?><file_sep><div class="panel panel-default">
<div class="panel-heading"><?php echo $key['name']; ?>: <?php echo date("d/m/Y H:i:s", $key['date']); ?></div>
<div class="panel-body" align="center">
<div align="left">
<?php echo $key['comment']; ?>
<?php
if ($status == 1 && $key['status'] == 0)
{
?>
<form action="<?php echo $this->base; ?>/admin/edit/<?php echo $id; ?>" method="post" data-ajax="false">
<input type="hidden" value="<?php echo $key['id']; ?>" name="edit[approve]">
<input type="submit" value="Approve" name="yes">
</form>
<?php } ?>
<form action="<?php echo $this->base; ?>/admin/edit/<?php echo $id; ?>" method="post" data-ajax="false">
<input type="hidden" value="<?php echo $key['id']; ?>" name="edit[delete]">
<input type="submit" value="Delete" name="yes">
</form>
<form action="<?php echo $this->base; ?>/admin/edit/<?php echo $id; ?>" method="post" data-ajax="false">
<input type="hidden" value="<?php echo $key['ip']; ?>" name="edit[ban]">
<input type="hidden" value="<?php echo $key['id']; ?>" name="edit[bandelete]">
<input type="submit" value="Ban" name="yes">
</form>
</div>
</div>
</div><file_sep><?php
class Sql {
function __construct()
{
require_once 'db.settings.php';
$this->status = $status;
$this->mysqli = new mysqli($host, $user, $password, $data);
if (mysqli_connect_error())
{
die('Server ERROR: (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
session_start();
}
// Добавляем в базу комментарий к новостям:
function addNewsComment($date, $name, $comment, $type, $ip, $url)
{
$this->mysqli->query("INSERT INTO news_comments(date, name, comment, type, status, ip, url) "
. "VALUES ('$date', '$name', '$comment', '$type', 0, '$ip', '$url')");
}
// Добавляем в базу комментарий:
function addComment($date, $name, $comment, $type, $ip)
{
if(!$this->mysqli->query("INSERT INTO comments(date, name, comment, type, status, ip) "
. "VALUES ('$date', '$name', '$comment', '$type', 0, '$ip')"))
{
return $this->mysqli->error;
}
}
// Выводим id последнего добавленного комментария к новостям
function getLastNewsCommentId()
{
$id = $this->mysqli->query("SELECT id from news_comments order by id desc limit 1");
$return = $id->fetch_object();
return $return->id;
}
// Выводим id последнего добавленного комментария
function getLastCommentId()
{
$id = $this->mysqli->query("SELECT id from comments order by id desc limit 1");
$return = $id->fetch_object();
return $return->id;
}
// Подписка на комментарии
function subscribe($unixtime, $name, $email, $lastid, $ipAddress)
{
$this->mysqli->query("INSERT INTO subscribe(date, name, email, status, lastid, ip) "
. "VALUES ('$unixtime', '$name', '$email', 1, '$lastid', '$ipAddress')");
}
// Отписка от комментариев
function unsubscribe($email)
{
$this->mysqli->query("DELETE from subscribe where email='$email'");
}
function status()
{
return $this->status;
}
// Проверка сессии
function checkSession()
{
$session = session_id();
$result = $this->mysqli->query("SELECT * FROM admin WHERE session='$session'");
$row = $result->fetch_assoc();
if ($row['session'] == $session)
{
return true;
}
else
{
return false;
}
}
function checkSubscribe($email)
{
$return = $this->mysqli->query("SELECT * from subscribe where email='$email'");
return $return->num_rows;
}
// Проверка пароля
function checkPassword($name)
{
$result = $this->mysqli->query("SELECT * FROM admin WHERE login='$name'");
$row = $result->fetch_assoc();
return ($row['password']);
}
//
function startSession($name)
{
$session = session_id();
$this->mysqli->query("UPDATE admin SET session = '$session' WHERE login='$name'");
}
function numPages()
{
$sql = $this->mysqli->query("SELECT id from comments");
return ceil($sql->num_rows / 10);
}
function numNews()
{
$sql = $this->mysqli->query("SELECT id from news");
return ceil($sql->num_rows / 10);
}
// Выводим количество комментариев к конкретной новости:
function numComments($url)
{
$sql = $this->mysqli->query("SELECT id from news_comments WHERE url='$url'");
return ceil($sql->num_rows / 10);
}
function announceCommentCounter($url)
{
$sql = $this->mysqli->query("SELECT id from news_comments WHERE url='$url'");
return $sql->num_rows;
}
// Удаляем запись из БД по заданному id:
function delete($id)
{
$result = $this->mysqli->query("SELECT * FROM comments WHERE id=$id");
if (@mysql_num_rows($result) < 1)
$this->mysqli->query("DELETE from comments where id=$id");
}
// Удаляем комментарий из новости
function newsCommentDelete($id)
{
$result = $this->mysqli->query("SELECT * FROM news_comments WHERE id=$id");
if (@mysql_num_rows($result) < 1)
$this->mysqli->query("DELETE from news_comments where id=$id");
}
// Проверяем, есть ли такой ip в списке забаненных
function checkBan($ip)
{
$checkip = $this->mysqli->query("SELECT * from ban where ip='$ip'");
return $checkip->num_rows;
}
function ban($ipAddress)
{
$checkip = $this->mysqli->query("SELECT * from ban where ip='$ipAddress'");
$row = $checkip->num_rows;
if ($row == 0)
$this->mysqli->query("INSERT INTO ban(ip) VALUES ('$ipAddress')");
return $row;
}
function approve($id)
{
$this->mysqli->query("UPDATE comments SET status=1 WHERE id='$id'");
}
// Редактируем текст новости
function updateNewsText($title, $description, $keyword, $url, $smalltext,
$maintext, $votequestion, $id)
{
// Фильтрация входящих данных:
$title = htmlspecialchars($this->mysqli->real_escape_string($title));
$description = htmlspecialchars($this->mysqli->real_escape_string($description));
$keyword = htmlspecialchars($this->mysqli->real_escape_string($keyword));
// Фильтруем лишнее в строке url,
// если фильтр не сработал, обзываем антитледом.
if(!$url = preg_replace('/[^a-zA-Z0-9-]/', '', $url))
$url = "untitled-".$id;
$smalltext = htmlspecialchars($this->mysqli->real_escape_string($smalltext));
$maintext = htmlspecialchars($this->mysqli->real_escape_string($maintext));
$votequestion = htmlspecialchars($this->mysqli->real_escape_string($votequestion));
if(!$this->mysqli->query("UPDATE news SET `Title`='$title', "
. "`Description`='$description', `Keyword`='$keyword', "
. "`URL`='$url', `Small text`='$smalltext', "
. "`Main text`='$maintext', `Vote question`='$votequestion' "
. "WHERE id=$id"))
{
return $this->mysqli->error;
}
}
// Добавляем текст новости
function addNewsText($title, $description, $keyword, $url, $smalltext, $maintext, $votequestion, $date)
{
if(!$this->mysqli->query("INSERT into news (`Title`, `Description`, `Keyword`, `URL`, `Small text`, `Main text`, `Vote question`, `date`) VALUES ('$title', '$description', '$keyword', '$url', '$smalltext', '$maintext', '$votequestion', '$date')"))
{
return $this->mysqli->error;
die;
}
}
function newsCommentApprove($id)
{
$this->mysqli->query("UPDATE news_comments SET status=1 WHERE id='$id'");
}
function select($id)
{
if ($id > 1)
{
$id = ($id - 1) * 10;
$sql = "SELECT * from comments order by id desc limit $id,10";
}
else
{
$sql = "SELECT * from comments order by id desc limit 10";
}
if ($result = $this->mysqli->query($sql))
{
while ($row = $result->fetch_assoc())
$rows[] = $row;
$result->free();
}
else
{
die($this->mysqli->error);
}
if (isset($rows))
return $rows;
}
// Постраничный вывод новостей
function selectNews($id)
{
if ($id > 1)
{
$id = ($id - 1) * 10;
$sql = "SELECT * from news order by id desc limit $id,10";
}
else
{
$sql = "SELECT * from news order by id desc limit 10";
}
if ($result = $this->mysqli->query($sql))
{
while ($row = $result->fetch_assoc())
$rows[] = $row;
$result->free();
}
else
{
die($this->mysqli->error);
}
if (isset($rows))
return $rows;
}
function newsComments($id, $url)
{
if ($id > 1)
{
$id = ($id - 1) * 10;
$sql = "SELECT * from news_comments WHERE url='$url' order by id desc limit $id,10";
}
else
{
$sql = "SELECT * from news_comments WHERE url='$url' order by id desc limit 10";
}
if ($result = $this->mysqli->query($sql))
{
while ($row = $result->fetch_assoc())
$rows[] = $row;
$result->free();
}
else
{
die($this->mysqli->error);
}
if (isset($rows))
return $rows;
}
// Проверка: голосовал ли конкретный ip в таком-то голосовании:
function checkVoteIp($vote, $ip)
{
$result = $this->mysqli->query("SELECT * FROM $vote WHERE ip='$ip'");
return $result->num_rows;
}
// Проверка: голосовал ли такой-то ip в голосовании под новостью:
function checkNewsVoteIp($url, $ip)
{
$result = $this->mysqli->query("SELECT * FROM news_votes WHERE ip='$ip' AND url='$url'");
return $result->num_rows;
}
// Внесение в базу результатов голосования
function vote($vote, $result, $ip)
{
$this->mysqli->query("INSERT INTO $vote (ip, result) VALUES ('$ip', '$result')");
}
// Внесение в базу результатов голосования под новостью
function newsVote($url, $result, $ip, $date)
{
$this->mysqli->query("INSERT INTO news_votes (date, url, result, ip) "
. "VALUES ('$date', '$url', '$result', '$ip')");
}
// Вывод результатов голосования
function voteCounter($vote)
{
$yes = $this->mysqli->query("SELECT result FROM $vote WHERE result=1");
$no = $this->mysqli->query("SELECT result FROM $vote WHERE result=2");
$result['yes'] = $yes->num_rows;
$result['no'] = $no->num_rows;
return $result;
}
// Вывод результатов голосования под новостью
function voteNewsCounter($url)
{
$yes = $this->mysqli->query("SELECT result FROM news_votes WHERE result=1 AND url='$url'");
$no = $this->mysqli->query("SELECT result FROM news_votes WHERE result=2 AND url='$url'");
$result['yes'] = $yes->num_rows;
$result['no'] = $no->num_rows;
return $result;
}
// Вывод общего количества новостей
function newsCounter()
{
$result = $this->mysqli->query("SELECT id FROM news");
return $result->num_rows;
}
// Вывод контента новостей
function getNews()
{
$result = $this->mysqli->query("SELECT * FROM news ORDER by id desc");
while ($row = $result->fetch_assoc())
$rows[] = $row;
return $rows;
}
// Вывод конкретной новости по url
function printArticle($url)
{
$result = $this->mysqli->query("SELECT * FROM news WHERE URL='$url'");
return $result->fetch_assoc();
}
function getNewsUrlById($id)
{
$result = $this->mysqli->query("SELECT * FROM news WHERE id='$id'");
return $result->fetch_assoc();
}
// Вывод конкретной новости по id
function printArticleById($id)
{
$result = $this->mysqli->query("SELECT * FROM news WHERE id='$id'");
return $result->fetch_assoc();
}
function activePage($id, $i)
{
if ($id == $i)
{
return "active";
}
}
function __destruct()
{
//$this->mysqli->close();
}
}
?><file_sep><div class="panel panel-default">
<div class="panel-heading"><?php echo $key['Vote question']; ?></div>
<div class="panel-body" align="center">
<div class="progress">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="84" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $yes; ?>%;">Yes <?php echo $yes; ?>% (<?php echo $voteResult['yes']; ?> Votes)</div>
</div>
<div class="progress">
<div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="16" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $no; ?>%;">No <?php echo $no; ?>% (<?php echo $voteResult['no']; ?> Votes)</div>
</div>
<form method="post">
<button type="submit" value="Yes" name="vote"
class="jqm-view-source-link ui-btn ui-corner-all ui-btn-inline ui-mini">Yes</button>
<button type="submit" value="No" name="vote"
class="jqm-view-source-link ui-btn ui-corner-all ui-btn-inline ui-mini">No</button>
</form>
</div>
</div><file_sep><div role="main" class="ui-content">
<div class="panel panel-default">
<div class="panel-heading">Add yourself | Stop censorship! | Image Upload</div>
<div class="panel-body">Make and upload your pic for support action.</div>
</div>
<div role="main" class="ui-content">
<form enctype="multipart/form-data" action="<?php echo $this->base; ?>/add/" method="post" data-ajax="false">
<input type="hidden" name="MAX_FILE_SIZE" value="3000000">
<input name="photo1" type="file" accept="image/*">
<input name="photo2" type="file" accept="image/*">
<input type="text" class="form-control" placeholder="Your name" name="comment[name]" required="">
<input type="text" class="form-control" placeholder="Your comment" name="comment[content]" required="">
<button type="submit" class="btn btn-success">Send</button>
</form>
</div>
</div>
<file_sep><div class="panel panel-default">
<div class="panel-heading">Do you support the legalization of public displaying and publication in the social networks of women's breasts?</div>
<div class="panel-body" align="center">
<div class="progress">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="84" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $yes; ?>%;">Yes <?php echo $yes; ?>% (<?php echo $voteResult['yes']; ?> Votes)</div>
</div>
<div class="progress">
<div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="16" aria-valuemin="0" aria-valuemax="100" style="width: <?php echo $no; ?>%;">No <?php echo $no; ?>% (<?php echo $voteResult['no']; ?> Votes)</div>
</div>
</div>
</div><file_sep><div role="main" class="ui-content">
<div class="panel panel-default">
<div class="panel-heading">Subscribe | Stop censorship!</div>
<div class="panel-body">Subscribe to new photos for support action.</div>
</div>
<div role="main" class="ui-content">
<form action="<?php echo $this->base; ?>/subscribe/" method="post" data-ajax="false">
<input type="email" class="form-control" placeholder="Your E-mail" name="subscribe[email]" required="">
<input type="text" class="form-control" placeholder="Your Name" name="subscribe[name]" required="">
<button type="submit" class="btn btn-success" name="subscribe[type]" value="yes">Subscribe</button>
<button type="submit" class="btn btn-warning" name="subscribe[type]" value="no">Unsubscribe</button>
</form>
</div>
</div><file_sep><?php
/*
* Database settings file
*/
// MySQL Server
$host = 'localhost';
// MySQL User
$user = 'comments';
// MySQL Password
$password = '<PASSWORD>';
// MySQL Database
$data = 'zadmin_comments';
$status = 1;<file_sep><?php
if ($pages == 1)
{
$class_prev = 'disabled';
$class_next = 'disabled';
$previous = $pages;
$next = $pages;
}
else
{
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$previous = $_GET['page'] - 1;
if (($_GET['page'] - 1) < 1)
{
$previous = 1;
$class_prev = 'disabled';
}
else
{
$previous = $_GET['page'] - 1;
}
if (($_GET['page'] + 1) <= $pages)
{
$next = $_GET['page'] + 1;
}
else
{
$class_next = 'disabled';
$next = $pages;
}
}
else
{
$class_prev = 'disabled';
$previous = 1;
$next = 2;
}
}
if(!isset($class_next))
$class_next = null;
if(!isset($class_prev))
$class_prev = null;
?>
<div class="text-center">
<nav>
<ul class="pagination">
<li class="<?php echo $class_prev; ?>">
<a class="ui-link-inherit" data-ajax="false" href="./?page=<?php echo $previous; ?>">
<span aria-hidden="true">«</span><span class="sr-only">Previous</span>
</a>
</li>
<?php
$i = 0;
while ($i != $pages)
{
$i++;
?>
<li class="<?php echo $view->activePage($id, $i); ?>">
<a class="ui-link-inherit" data-ajax="false" href="./?page=<?php echo $i; ?>"><?php echo $i; ?></a>
</li>
<?php
}
?>
<li class="<?php echo $class_next; ?>">
<a class="ui-link-inherit" data-ajax="false" href="./?page=<?php echo $next; ?>">
<span aria-hidden="true">»</span><span class="sr-only">Next</span>
</a>
</li>
</ul>
</nav>
</div><file_sep><div data-role="page" id="<?php echo $pageId; ?>">
<div style="width: 100%; max-width: 1100px; margin: 0 auto;">
<div role="main" class="ui-content">
<div class="panel panel-default">
<div class="panel-heading"><?php echo $panelHeading; ?></div>
<div class="panel-body"><?php echo $panelBody; ?></div>
</div>
<?php echo $content; ?>
</div>
</div>
</div><file_sep><?php
//error_reporting(E_ALL);
date_default_timezone_set('UTC');
// Мета-теги для страницы:
$title = 'Subscribe | Stop censorship!';
$keywords = 'free the nipple, #freethenipple, stop censorship, naked, woman, boobs, tits';
$description = 'Why we can look at the scenes of violence and cruelty, and can not look at a naked woman?';
// Подключаем классы
require_once 'class.Sql.php';
require_once 'class.Render.php';
$view = new Sql();
$render = new Render();
$pages = $view->numPages();
$newsCount = $view->newsCounter();
// Ссылки:
$links = array(
'Free the nipple' => array(
'url' => 'index.php',
'class' => '',
),
'Add comment' => array(
'url' => 'add/',
'class' => '',
),
'Related news (' . $newsCount . ')' => array(
'url' => 'announce/',
'class' => '',
),
'Subscribe' => array(
'url' => 'subscribe/',
'class' => 'ui-btn-active',
),
);
$ipAddress = $_SERVER['REMOTE_ADDR'];
$date = new DateTime();
$unixtime = $date->getTimestamp();
// Обработчик подписки
if (!empty($_POST['subscribe']['email']) &&
!empty($_POST['subscribe']['name']) && $_POST['subscribe']['type'] == "yes")
{
$email = filter_var($_POST['subscribe']['email'], FILTER_SANITIZE_EMAIL);
$name = filter_var($_POST['subscribe']['name'], FILTER_SANITIZE_STRING);
// Проверяем есть ли такой email
$mailcount = $view->checkSubscribe($email);
if ($mailcount == 0)
{
// Получаем последний id из комментов
$lastid = $view->getLastCommentId();
// Подписываем:
$view->subscribe($unixtime, $name, $email, $lastid, $ipAddress);
}
}
// Обработчик отписки
if (!empty($_POST['subscribe']['email']) && $_POST['subscribe']['type'] == "no")
{
$email = filter_var($_POST['subscribe']['email'], FILTER_SANITIZE_EMAIL);
// Проверяем есть ли такой email
$mailcount = $view->checkSubscribe($email);
if ($mailcount != 0)
{
// Удаляем
$view->unsubscribe($email);
}
}
if (empty($_POST['subscribe']))
{
$render->header($newsCount, $title, $description, $keywords, $links);
$render->body('subscribe');
$render->footer();
}
else
{
header("Location: ../");
die;
}
?><file_sep><?php
/*
* Вывод отдельной новости
*
*/
error_reporting(E_ALL);
date_default_timezone_set('UTC');
// Мета-теги для страницы:
$title = 'Free the nipple | Stop censorship!';
$keywords = 'free the nipple, #freethenipple, stop censorship, naked, woman, boobs, tits';
$description = 'Why we can look at the scenes of violence and cruelty, and can not look at a naked woman?';
require_once 'class.Sql.php';
require_once 'class.Render.php';
$view = new Sql();
$render = new Render();
$newsCount = $view->newsCounter();
// Ссылки:
$links = array(
'Free the nipple' => array(
'url' => 'index.php',
'class' => '',
),
'Add comment' => array(
'url' => 'add/',
'class' => '',
),
'Related news (' . $newsCount . ')' => array(
'url' => 'announce/',
'class' => 'ui-btn-active',
),
'Subscribe' => array(
'url' => 'subscribe/',
'class' => '',
),
);
if (isset($_GET['url']) && filter_var($_GET['url'], FILTER_SANITIZE_STRING))
{
// Инит переменных
$datetime = new DateTime();
$date = $datetime->getTimestamp();
$ip = $_SERVER['REMOTE_ADDR'];
$url = filter_var($_GET['url'], FILTER_SANITIZE_STRING);
$vote = $url;
if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0)
$id = $_GET['page'];
else
$id = 1;
// Обработчик добавления комментариев
if ($view->checkBan($ip) == 0)
{
if (!empty($_POST['comment']['name']) &&
!empty($_POST['comment']['content']) &&
!empty($_FILES['photo1']['name']) &&
!empty($_FILES['photo2']['name']) &&
!empty($_POST['comment']['type']) &&
$_POST['comment']['type'] = 1)
{
$extension1 = explode(".", $_FILES['photo1']['name']);
$extension2 = explode(".", $_FILES['photo2']['name']);
$uploadfile = md5(rand() . $_FILES['photo1']['name']) . '.' . $extension1[1];
$uploadfile2 = md5(rand() . $_FILES['photo2']['name']) . '.' . $extension2[1];
if (move_uploaded_file($_FILES["photo1"]['tmp_name'], $uploadfile) &&
move_uploaded_file($_FILES["photo2"]['tmp_name'], $uploadfile2))
{
$name = filter_var($_POST['comment']['name'], FILTER_SANITIZE_STRING);
$comment = filter_var($_POST['comment']['content'], FILTER_SANITIZE_STRING);
// Images:
$ext = array(IMAGETYPE_GIF, IMAGETYPE_JPEG);
$a = getimagesize($uploadfile);
$b = getimagesize($uploadfile2);
if (!$a || !$b)
{
die('error getimagesize');
}
if (in_array($a[2], $ext) && in_array($b[2], $ext))
{
$view->addNewsComment($date, $name, $comment, 1, $ip, $url);
// Convert
exec('ffmpeg -i ' . $uploadfile . ' -pix_fmt rgb24 -vf "scale=-1:500" ./img/' . $view->getLastNewsCommentId() . '_1.gif');
unlink($uploadfile);
exec('ffmpeg -i ' . $uploadfile2 . ' -pix_fmt rgb24 -vf "scale=-1:500" ./img/' . $view->getLastNewsCommentId() . '_2.gif');
unlink($uploadfile2);
}
else
{
@unlink($uploadfile);
@unlink($uploadfile2);
die('unsupported file type');
}
}
else
{
header("location: ./");
die;
}
}
elseif (!empty($_POST['comment']['name']) &&
!empty($_POST['comment']['content']) &&
!empty($_FILES['photo1']['name']) &&
!empty($_POST['comment']['type']) &&
$_POST['comment']['type'] = 1)
{
$extension1 = explode(".", $_FILES['photo1']['name']);
$uploadfile = md5(rand() . $_FILES['photo1']['name']) . '.' . $extension1[1];
if (move_uploaded_file($_FILES["photo1"]['tmp_name'], $uploadfile))
{
$name = filter_var($_POST['comment']['name'], FILTER_SANITIZE_STRING);
$comment = filter_var($_POST['comment']['content'], FILTER_SANITIZE_STRING);
// Images:
$ext = array(IMAGETYPE_GIF, IMAGETYPE_JPEG);
$a = getimagesize($uploadfile);
if (!$a)
{
die('error getimagesize');
}
if (in_array($a[2], $ext))
{
$view->addNewsComment($date, $name, $comment, 1, $ip, $url);
// Convert
exec('ffmpeg -i ' . $uploadfile . ' -pix_fmt rgb24 -vf "scale=-1:500" ./img/' . $view->getLastNewsCommentId() . '_1.gif');
unlink($uploadfile);
}
else
{
@unlink($uploadfile);
die('unsupported file type');
}
}
else
{
header("location: ./");
die;
}
}
elseif (!empty($_POST['comment']['name']) &&
!empty($_POST['comment']['content']) &&
!empty($_FILES['photo2']['name']) &&
!empty($_POST['comment']['type']) &&
$_POST['comment']['type'] = 1)
{
$extension2 = explode(".", $_FILES['photo2']['name']);
$uploadfile2 = md5(rand() . $_FILES['photo2']['name']) . '.' . $extension2[1];
if (move_uploaded_file($_FILES["photo2"]['tmp_name'], $uploadfile2))
{
$name = filter_var($_POST['comment']['name'], FILTER_SANITIZE_STRING);
$comment = filter_var($_POST['comment']['content'], FILTER_SANITIZE_STRING);
// Images:
$ext = array(IMAGETYPE_GIF, IMAGETYPE_JPEG);
$b = getimagesize($uploadfile2);
if (!$b)
{
die('getimagesize error');
}
if (in_array($b[2], $ext))
{
// Добавляем коммент с одной картинкой:
$view->addNewsComment($date, $name, $comment, 1, $ip, $url);
exec('ffmpeg -i ' . $uploadfile2 . ' -pix_fmt rgb24 -vf "scale=-1:500" ./img/' . $view->getLastNewsCommentId() . '_2.gif');
unlink($uploadfile2);
}
else
{
@unlink($uploadfile2);
die('unsupported file type');
}
}
else
{
header("location: ./");
die;
}
}
// Действие, если комментарий без картинок
else if (!empty($_POST['comment']['name']) &&
!empty($_POST['comment']['content']) &&
!empty($_POST['comment']['type']) && $_POST['comment']['type'] = 2)
{
$name = filter_var($_POST['comment']['name'], FILTER_SANITIZE_STRING);
$comment = filter_var($_POST['comment']['content'], FILTER_SANITIZE_STRING);
$view->addNewsComment($date, $name, $comment, 2, $ip, $url);
}
}
// Вывод контента новости:
if ($key = $view->printArticle($url))
{
// Вывод верхней части страницы:
/* Подсчёт количества новостей и вывод в шапку */
$newsCount = $view->newsCounter();
$render->header($newsCount, $key['Title'], $key['Description'], $key['Keyword'], $links);
$pages = $view->numComments($url);
if($pages > 0)
$render->newsPagination($view, $pages, $url);
require_once './tpl/news/article.php';
// Обработчик голосования:
if (isset($_POST['vote']))
{
// Проверяем, голосовал ли этот Ip:
$result = $view->checkNewsVoteIp($url, $ip);
if ($result == 0)
{
switch ($_POST['vote'])
{
case 'Yes':
$view->newsVote($url, 1, $ip, $date);
break;
case 'No':
$view->newsVote($url, 2, $ip, $date);
break;
}
}
}
// Обработчик вывода результатов голосования:
$voteResult = $view->voteNewsCounter($url);
if ($voteResult['yes'] + $voteResult['no'] != 0)
{
$all = 100 / ($voteResult['yes'] + $voteResult['no']);
$yes = round($voteResult['yes'] * $all, 1);
$no = round($voteResult['no'] * $all, 1);
}
else
{
$yes = 100;
$no = 100;
$voteResult['yes'] = 0;
$voteResult['no'] = 0;
}
// Обработчик вывода формы для голосования:
$result = $view->checkNewsVoteIp($url, $ip);
if ($result == 0)
{
// Раз этот ip не голосовал, выводим ему кнопочки
include './tpl/news/unvoted.block.php';
}
else
{
// Этот ip уже голосовал, кнопочки скрываем
include './tpl/news/voted.block.php';
}
// Показ формы для комментирования новости
$render->commentForm("news", $url);
// Вывод блока комментариев:
if ($view->newsComments($id, $url))
foreach ($view->newsComments($id, $url) as $key)
$render->imageBlock("news", $key);
// Пагинация для комментариев
if($pages > 0)
$render->newsPagination($view, $pages, $url);
}
else
{
require_once './tpl/errors/page.not.found.php';
}
}
$render->footer();
|
835bce2ee25283109ab001b637f760d85f122873
|
[
"Markdown",
"PHP"
] | 28
|
PHP
|
kesenai/freethenipple
|
efc620e68736496aa301416a4e2900da72f06c70
|
f0d25a53e45e50c367ed653e391b149565309369
|
refs/heads/master
|
<file_sep><?php
/*
Group 13
September 29, 2016
WEBD3201
The Welcome Page
*/
$title = "Welcome";
$date = "September 29, 2016";
$filename = "index.php";
$description = " A page that welcomes the agent";
include("header.php");
?>
<?php
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$_SESSION['previousPage'] = $actual_link;
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['user_type'] == GET_ADMIN)
{
//SQL code
$sql = "SELECT * FROM users JOIN people ON users.user_id = people.user_id WHERE user_type='".GET_DISABLED."' ORDER BY users.user_id ";
$result = pg_query(db_connect(), $sql. " LIMIT 200 ");
$records = pg_num_rows($result);
echo "<br/><br/>";
$search = $sql;
if (isset($_GET ['submit']))
{
$button = $_GET ['submit'];
$search = $sql;
}
$search_exploded = explode (" ", $search);
$x = "";
$construct = $sql;
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="title LIKE '%$search_each%'";
else
$construct .="AND title LIKE '%$search_each%'";
}
//USED TO MAKE THE NUMBER OF PAGINATE
$constructs = $sql;
$run = pg_query(db_connect(),$constructs);
$foundnum = pg_num_rows($run);
//Shows the number of results match the criteria
echo "<h2 align=\"center\">Show Disabled Users </h2>";
//echo "<p>$foundnum results found !<p>";
//sets the number of houses per pages
$per_page = PAGE_LIMIT;
$start = isset($_GET['start']) ? $_GET['start']: 0;
//find the appropriate number of pages needed to display the page
$max_pages = ceil($foundnum / $per_page);
//Page starts at the first records
if(!$start)
$start=0;
//Set up the query
$getquery = pg_query(db_connect(), $sql. " LIMIT $per_page OFFSET $start");
//_______________________________________________________________________________________________________CREATES THE TABLE
echo "\n<table border=\"0\">";
$i=0;
if ($i == 0)
{
echo "<tr><th>User ID</th><th>Full Name</th></tr>";
}
while($runrows = pg_fetch_assoc($getquery))
{
$user_id = $runrows['user_id'];
$firstName = $runrows['first_name'];
$lastName = $runrows['last_name'];
$i +=1;
echo "\n<tr><td> ";
echo "$user_id";
echo "\n</td>";
echo "\n<td >";
echo "<br/>$firstName $lastName ";
echo "\n </tr>";
echo "\n<tr><td colspan=\"2\">";
echo "\n\t<hr/>";
echo "\n</td></tr>";
}
echo "\n</table>";
//Pagination Starts
echo "<center>";
$prev = $start - $per_page;
$next = $start + $per_page;
$adjacents = 3;
$last = $max_pages - 1;
if($max_pages > 1)
{
//previous button
if (!($start<=0))
echo " <a href='disabled-users.php?submit=Search+source+code&start=$prev'>Prev</a> ";
//In the first 6 pages, it doesn't skip
if ($max_pages < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='disabled-users.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='disabled-users.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
elseif($max_pages > 5 + ($adjacents * 2)) //enough pages to hide some but the first two and the next 3 pages
{
//close to beginning; only hide later pages
if(($start/$per_page) < 1 + ($adjacents * 2))
{
$i = 0;
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($i == $start){
echo " <a href='disabled-users.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='disabled-users.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//in middle; hide some front and some back
elseif($max_pages - ($adjacents * 2) > ($start / $per_page) && ($start / $per_page) > ($adjacents * 2))
{
echo " <a href='disabled-users.php?submit=Search+source+code&start=0'>1</a> ";
echo " <a href='disabled-users.php?submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start/$per_page)+1; $counter < ($start / $per_page) + $adjacents + 2; $counter++)
{
if ($i == $start){
echo " <a href='disabled-users.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='disabled-users.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//close to end; only hide early pages
else
{
echo " <a href='disabled-users.php?submit=Search+source+code&start=0'>1</a> ";
echo " <a href='disabled-users.php?submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start / $per_page) + 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='disabled-users.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='disabled-users.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
}
//next button
if (!($start >=$foundnum-$per_page))
echo " <a href='disabled-users.php?submit=Search+source+code&start=$next'>Next</a> ";
}
echo "</center>";
echo "</form>";
echo "<br/>";
}
?>
<?php include 'footer.php'; ?><file_sep><?php
/*
Group 13
September 29, 2016
--WEBD3201
*/
//Login
pg_prepare(db_connect(), "Log_In_query", 'SELECT * FROM users WHERE user_id = $1 AND password = $2');
//Update users last login access
pg_prepare(db_connect(),"UpdateUserDate","UPDATE users SET last_access = '" . date("Y-m-d",time()) . "' WHERE user_id = $1");
//checks if username is found atleast but wrong password
pg_prepare(db_connect(), "user_check", 'SELECT * FROM users WHERE user_id = $1');
//INSERT NEW USER IN USERS TABLE
pg_prepare(db_connect(), "insert_user", 'INSERT INTO users VALUES($1, $2, $3, $4, $5, $6)');
//INSERT NEW USER IN PEOPLE TABLE
pg_prepare(db_connect(), "insert_people", 'INSERT INTO people VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)');
//INSERT NEW LISTING IN TABLE
pg_prepare(db_connect(), "insert_listings", 'INSERT INTO listings VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18)');
// Updates user password
pg_prepare(db_connect(), "update_user_pass", 'UPDATE users SET password = $1 WHERE user_id = $2 AND password = $3');
//Get Personal
pg_prepare(db_connect(), "Get_Personal", 'SELECT * FROM people WHERE user_id = $1');
//Password change request
pg_prepare(db_connect(), "update_password_request", 'UPDATE users SET password = $1 WHERE user_id = $2 AND email_address = $3');
//Update Email/Users table
pg_prepare(db_connect(), "update_users", 'UPDATE users SET email_address = $1 WHERE user_id = $2');
//Update Peoples Table
pg_prepare(db_connect(), "update_people", 'UPDATE people SET salutation = $1, first_name=$2, last_name=$3, street_address_1 = $4, street_address_2=$5, city=$6, province=$7, postal_code=$8, primary_phone_number=$9, secondary_phone_number=$10, fax_number=$11, preferred_contact_method=$12 WHERE user_id = $13');
//Update Listing Images
pg_prepare(db_connect(), "update_image", 'UPDATE listings SET images=$1 WHERE listing_id=$2');
//Update Listing
pg_prepare(db_connect(), "update_listings", 'UPDATE listings SET status=$1, price=$2, headline=$3, description=$4, postal_code=$5, city=$6, property_options=$7, bedrooms=$8, bathrooms=$9, garage=$10, purchase_type=$11, property_type=$12, finished_basement=$13, open_house=$14, schools=$15 WHERE listing_id=$16');
//Get Listing Information
pg_prepare(db_connect(), "get_listing", 'SELECT * FROM listings WHERE listing_id=$1');
function db_connect()
{
return pg_connect("host=".HOST_DB." dbname=".NAME_DB." user=".USER_DB." password=".PASSWORD_DB."" );
}
function is_user_id($id)
{
$result = pg_execute(db_connect(),"user_check",array($id));
$records = pg_num_rows($result);
if ( $records == 1)
{
return true;
}
else
{
return false;
}
}
function build_simple_dropdown($table,$selected)
{
$sql = 'SELECT * FROM '.$table;
$output = "";
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
$output .= "\n<select name = \"".$table."\">";
$output .= "\n<option value = \"\"></option>";
for($i = 0; $i < $records; $i++)
{
$checked = (pg_fetch_result($result, $i, "value") == $selected)? "selected":"";
$output .= "\n<option value = '".pg_fetch_result($result, $i, "value")."' ".$checked." >".pg_fetch_result($result, $i, "value")."</option>";
//$records['value']
}
$output .= "\n</select>";
return $output;
}
function build_dropdown($table,$selected)
{
$sql = 'SELECT * FROM '.$table;
$output = "";
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
$output .= "\n<select name = \"".$table."\">";
$output .= "\n<option value = \"\"></option>";
for($i = 0; $i < $records; $i++)
{
$checked = (pg_fetch_result($result, $i, "value") == $selected)? "selected":"";
$output .= "\n<option value = '".pg_fetch_result($result, $i, "value")."' ".$checked." >".pg_fetch_result($result, $i, "property")."</option>";
//$records['value']
}
$output .= "\n</select>";
return $output;
}
function build_radio($table,$selected)
{
$sql = 'SELECT * FROM '.$table;
$output = "";
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
for($i = 0; $i < $records; $i++){
$checked = (pg_fetch_result($result, $i, "value") == $selected)? "checked":"";
$output .= "\n<label><input type=\"radio\" name=\"".$table."\" value=\"".pg_fetch_result($result, $i, "value")."\" ".$checked."/><span>".pg_fetch_result($result, $i, "property")."</span></label>";
}
return $output;
}
function get_property($table,$value)
{
$sql = 'SELECT * FROM '.$table;
$output = "";
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
for($i = 0; $i < $records; $i++)
{
$output .= (pg_fetch_result($result, $i, "value") == $value)? pg_fetch_result($result, $i, "property") :"";
}
return $output;
}
function build_checkbox($table,$preselected)
{
$sql = 'SELECT * FROM '.$table;
$output = "";
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
for($i = 0; $i < $records; $i++){
$checked = isBitSet($i, $preselected)? " checked=\"checked\" ": "";
$output .= "\n<label><input type=\"checkbox\" name=\"".$table."[]\" value=\"".pg_fetch_result($result, $i, "value")."\" ".$checked."/> <span> ".pg_fetch_result($result, $i, "property")."</span></label>";
}
return $output;
}
?><file_sep>--Group 13
--schools.sql
--October 19, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS schools;
--Creates the table again
CREATE TABLE schools(
value INT PRIMARY KEY,
property VARCHAR(30) NOT NULL
);
--Inserts rows inside the table
INSERT INTO schools (value, property) VALUES (1, 'Yes');
INSERT INTO schools (value, property) VALUES (2, 'No');<file_sep>--Group 13
--washrooms.sql
--October 19, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS washrooms;
--Creates the table again
CREATE TABLE washrooms(
value INT PRIMARY KEY,
property VARCHAR(30) NOT NULL
);
--Inserts rows inside the table
INSERT INTO washrooms (value, property) VALUES (1, '1');
INSERT INTO washrooms (value, property) VALUES (2, '2');
INSERT INTO washrooms (value, property) VALUES (4, '3');
INSERT INTO washrooms (value, property) VALUES (8, '4');
INSERT INTO washrooms (value, property) VALUES (16, '5 or more');<file_sep><?php
/*
Group_13
November 22, 2016
WEBD3201
Password Request page
*/
$title = "Password Request";
$date = "November 22, 2016";
$filename = "password-request.php";
$description = "The password request page ";
include("header.php");
?>
<?php
//empty out error and result regardless of method that got you here
$error = "";
$output = "";
//Redirects anyone that trys to backdoor
if ( isset($_SESSION['loggedin']) )
{
//------------------------------------------------------------------------------------------------------------------------------------AGENT
if ($_SESSION['user_type'] == GET_AGENT)
{
header("Location: dashboard.php");
}
//------------------------------------------------------------------------------------------------------------------------------------USER
else if($_SESSION['user_type'] == GET_USER)
{
header("Location: welcome.php");
}
//------------------------------------------------------------------------------------------------------------------------------------ADMIN
else if($_SESSION['user_type'] == GET_ADMIN)
{
header("Location: admin.php");
}
}
if($_SERVER["REQUEST_METHOD"] == "GET")
{
//default mode when the page loads the first time
//can be used to make decisions and initialize variables
$id = "";
$email = "";
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
//the page got here from submitting the form, let's try to process
$id = trim($_POST["id"]); //the name of the input box on the form, white-space removed
$email = trim($_POST["email"]); //the name of the input box on the form, white-space removed
$headers = 'From: <EMAIL>';
$subject = "Password Changed";
if ($id == "")
{
$error .= "<br/>User ID cannot be empty";
}
if ($email == "")
{
$error .= "<br/>Email cannot be empty";
}
if ($error == "")
{
$sql = "SELECT * FROM users WHERE user_id = '$id'";
$result = pg_query(db_connect(),$sql);
$records = pg_num_rows($result);
if ($records == 1)
{
if ($email == pg_fetch_result($result, 0, "email_address") )
{
$output = "Email match";
$sql = "SELECT * FROM people WHERE user_id = '$id'";
$people = pg_query(db_connect(),$sql);
$firstName = pg_fetch_result($people, 0, "first_name");
$lastName = pg_fetch_result($people, 0, "last_name");
$salutation = pg_fetch_result($people, 0, "salutation");
$newPassword = <PASSWORD>();
// the message
$msg = "<img src=\"images/LogoFinal2.png\" width=\"200px\" /><br/>Hello $salutation $firstName $lastName,<br/> Your account for ".WEBSITE_NAME." has recently requested a new password, please use this new password <b> $newPassword </b> to login in. <br/>If you didn't request for an password change, don't worry! Please contact us right away to secure your account <br/><br/>Sincerely, <br/>".WEBSITE_NAME." <br/><br/>Request made: ".date("Y-m-d h:i:sa",time());
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);
//echo $msg;
// send email
//mail($email,$subject,$msg,$headers);
//Hashs password
$hashedPassword = hash("md5", $new<PASSWORD>);
//Execute new password to database
pg_execute(db_connect(),"update_password_request",array($hashedPassword,$id,$email,));
//Creates message for user
$_SESSION['message'] = "Email has been sent to $email, check for the new password there.";
//Relocates to login page
//header("Location: login.php");
}
else
{
$error .= "Email does not match the account";
}
}
else
{
$error .= "User ID does not exist";
}
}
}
?>
<h1>Password Request</h1>
<hr/>
<p>If you know your password and want to login, please go to the <a href="./login.php">login</a> page on the top bar.
<br/>
</p>
<h2 style="text-align: center;"><?php echo $output; ?></h2>
<h3 style="text-align: center;"><?php echo $error; ?></h3>
<p style="text-align: center;">Enter your login ID and email to request a password</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table style="border: none;
background-color: #e5f2ff;
width: auto;
text-align: center;
margin-left: auto;
margin-right: auto;" cellspacing="15">
<tr>
<td>
Login ID:
</td>
<td><input type="text" name="id" value="<?php echo $id; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td>Email:
</td>
<td><input type="text" name="email" value="<?php echo $email; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Request Password" /></td>
</tr>
</table>
</form>
<br/>
<?php include 'footer.php'; ?><file_sep><?php
/*
Group 13
September 29, 2016
--WEBD3201
*/
//Dataconnect CONSTANTS
define("HOST_DB", "ec2-3-221-238-58.compute-1.amazonaws.com");
define("NAME_DB", "dbs213q5ubcs99");
define("USER_DB", "myycaiegetxgyz");
define("PASSWORD_DB", "<PASSWORD>");
//For registeration
define("MINIMUM_ID_LENGTH", 5);
define("MAXIMUM_ID_LENGTH", 20);
define("MINIMUM_PASSWORD_LENGTH", 6);
define("MAXIMUM_PASSWORD_LENGTH", 32);
define("MAX_FIRST_NAME_LENGTH", 25);
define("MAX_LAST_NAME_LENGTH", 50);
define("MAXIMUM_EMAIL_LENGTH", 255);
define("MAXIMUM_POSTAL_LENGTH", 6);
define("MAXIMUM_STREET_LENGTH", 75);
define("MINIMUM_PHONE_LENGTH", 200);
define("WEBSITE_NAME", "Houses Connected");
//User_Type constants
define("GET_ADMIN", "A");
define("GET_AGENT", "R");
define("GET_PENDING", "P");
define("GET_DISABLED", "D");
define("GET_USER", "U");
define("GET_INCOMPLETE", "I");
//Contact_Methods
define("EMAIL", "E");
define("PHONE", "P");
define("MAIL", "M");
define("TEXT", "T");
//Listing Status
define("OPEN", "O");
define("CLOSED", "C");
define("SOLD", "S");
define("HIDDEN", "H");
define("DISABLED", "D");
//How many previews are shown on one page
define("PAGE_LIMIT", 10);
//Image Size Limit
define("IMAGE_SIZE_LIMIT", 1000000);
//Limit the amount of images can be saved in folder
define("IMAGE_AMOUNT_LIMIT", 7);
//This is used for the cookie length, 86400 is the total seconds within 24 hours and second number is the number of days
define("COOKIE_LENGTH", (86400 * 30))
?><file_sep><?php
/*
Group 13
November 10, 2016
WEBD3201
The Listing search page
*/
$title = "Listing Search";
$date = "November 10, 2016";
$filename = "index.php";
$description = "The Listing search page";
include("header.php");
?>
<?php
$error = "";
$output = "";
$bed_table = 'bedrooms';
$wash_table = 'washrooms';
$open_table = 'open_house';
$base_table = 'finished_basement';
$type_table = 'purchase_type';
$property_table = 'property_type';
$city_table = 'cities';
$garage_table = 'garage_type';
$options_table = 'property_options';
$schools_table = 'schools';
$beds = (isset($_COOKIE[$bed_table]))?$_COOKIE[$bed_table]:0;
$wash = (isset($_COOKIE[$wash_table]))?$_COOKIE[$wash_table]:0;
$open = (isset($_COOKIE[$open_table]))?$_COOKIE[$open_table]:0;
$base = (isset($_COOKIE[$base_table]))?$_COOKIE[$base_table]:0;
$purchase = (isset($_COOKIE[$type_table]))?$_COOKIE[$type_table]:0;
$minimum = (isset($_COOKIE['min']))?$_COOKIE['min']:""; ;
$maximum = (isset($_COOKIE['max']))?$_COOKIE['max']:""; ;
$property_type = (isset($_COOKIE[$property_table]))?$_COOKIE[$property_table]:0;
$garage = (isset($_COOKIE[$garage_table]))?$_COOKIE[$garage_table]:0;
$options = (isset($_COOKIE[$options_table]))?$_COOKIE[$options_table]:0;
$schools = (isset($_COOKIE[$schools_table]))?$_COOKIE[$schools_table]:0;
if(!isset($city))//___________________________________________CITY
{
$city=0;
}
if (isset($_SESSION['city']) )
{
$city = $_SESSION['city'];
}
if($_SERVER["REQUEST_METHOD"] == "GET")
{
//default mode when the page loads the first time
//can be used to make decisions and initialize variables
//ROW 2
if (isset($_GET['city']))
{
$_SESSION['city'] = $_GET['city'];
}
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
$minimum = trim($_POST['minimum']);
$maximum = trim($_POST['maximum']);
if (isset($_POST[$bed_table])) //___________________________BEDS
{
$beds = sumCheckBox($_POST[$bed_table]);
setcookie($bed_table, $beds, time()+ COOKIE_LENGTH, "/");
}
else
{
$beds = 0;
setcookie($bed_table, $beds, time()+ COOKIE_LENGTH, "/");
}
if (isset($_POST[$wash_table])) //___________________________WASHROOM
{
$wash = sumCheckBox($_POST[$wash_table]);
setcookie($wash_table, $wash, time()+ COOKIE_LENGTH, "/");
}
else
{
$wash = 0;
setcookie($wash_table, $wash, time()+ COOKIE_LENGTH, "/");
}
if (isset($_POST[$open_table])) //___________________________OPEN HOUSE
{
$open = sumCheckBox($_POST[$open_table]);
setcookie($open_table, $open, time()+ COOKIE_LENGTH, "/");
}
else
{
$open = 0;
setcookie($open_table, $open, time()+ COOKIE_LENGTH, "/");
}
if (isset($_POST[$base_table])) //___________________________BASEMENT OR NOT
{
$base = sumCheckBox($_POST[$base_table]);
setcookie($base_table, $base, time()+ COOKIE_LENGTH, "/");
}
else
{
$base = 0;
setcookie($base_table, $base, time()+ COOKIE_LENGTH, "/");
}
if (isset($_POST[$type_table])) //___________________________TYPE OF PURCHASE, rent or sale
{
$purchase = sumCheckBox($_POST[$type_table]);
setcookie($type_table, $purchase, time()+ COOKIE_LENGTH, "/");
}
else
{
$purchase = 0;
setcookie($type_table, $purchase, time()+ COOKIE_LENGTH, "/");
}
//_________________________________________________________________________PRICE MINIMUM
//minimum validate
if(strlen($minimum) > 0 && !is_numeric($minimum))
{
//means the user did not enter any dap
$error .= "Minimum price must be a number. <br/>";
}
//_________________________________________________________________________PRICE MAXIMUM
//maximum validate
if(strlen($maximum) > 0 && !is_numeric($maximum))
{
//means the user did not enter any dap
$error .= "Maximum price must be a number. <br/>";
}
if ($error == "")
{
setcookie('min', $minimum, time()+ COOKIE_LENGTH, "/");
setcookie('max', $maximum, time()+ COOKIE_LENGTH, "/");
}
if (isset($_POST[$property_table])) //___________________________PROPERTY TYPE
{
$property_type = sumCheckBox($_POST[$property_table]);
setcookie($property_table, $property_type, time()+ COOKIE_LENGTH, "/");
}
else
{
$property_type = 0;
setcookie($property_table, $property_type, time()+ COOKIE_LENGTH, "/");
}
if (isset($_POST[$garage_table])) //___________________________GARAGE TYPE FOR THE HOUSE
{
$garage = sumCheckBox($_POST[$garage_table]);
setcookie($garage_table, $garage, time()+ COOKIE_LENGTH, "/");
}
else
{
$garage = 0;
setcookie($garage_table, $garage, time()+ COOKIE_LENGTH, "/");
}
if (isset($_POST[$options_table])) //___________________________OPTION TYPE
{
$options = sumCheckBox($_POST[$options_table]);
setcookie($options_table, $options, time()+ COOKIE_LENGTH, "/");
}
else
{
$options = 0;
setcookie($options_table, $options, time()+ COOKIE_LENGTH, "/");
}
if (isset($_POST[$schools_table])) //___________________________SCHOOLS
{
$schools = sumCheckBox($_POST[$schools_table]);
setcookie($schools_table, $schools, time()+ COOKIE_LENGTH, "/");
}
else
{
$schools = 0;
setcookie($schools_table, $schools, time()+ COOKIE_LENGTH, "/");
}
echo $city;
if ( ($city == 0))
{
$error .= "No city was chosen";
}
//_________________________________________________________________________________________________________AFTER EVERYTHING IS SET, IT WOULD TRANSFER ACROSS TO LISTING-MATCHES
//___________________________________________________________________________________________CREATE WHERE STATEMENT
if ($error == "")
{
$_SESSION['WhereStarted'] = true;
$sqlPrepare = "";
$sqlPrepare .= makeWhereStatement($bed_table, $beds, "bedrooms");
$sqlPrepare .= makeWhereStatement($wash_table, $wash, "bathrooms");
$sqlPrepare .= makeWhereStatement($open_table, $open, "open_house");
$sqlPrepare .= makeWhereStatement($base_table, $base, "finished_basement");
$sqlPrepare .= makeWhereStatement($type_table, $purchase, "purchase_type");
if (strlen($minimum) > 0) //_________________________________________________MINIMUM
{
if ($_SESSION['WhereStarted'] == true)
{
$sqlPrepare .= " WHERE (price >= $minimum) ";
//echo " WHERE (price >= $minimum) ";
}
else
{
$sqlPrepare .= " AND (price >= $minimum) ";
//echo "AND (price >= $minimum) ";
}
$_SESSION['WhereStarted'] = false;
}
if (strlen($maximum) > 0) //____________________________________________________MAXIMUM
{
if ($_SESSION['WhereStarted'] == true)
{
$sqlPrepare .= "WHERE (price <= $maximum) ";
//echo "WHERE (price <= $maximum)";
}
else
{
$sqlPrepare .= "AND (price <= $maximum) ";
//echo " AND (price <= $maximum)";
}
$_SESSION['WhereStarted'] = false;
}
$sqlPrepare .= makeWhereStatement($property_table, $property_type, "property_type");
$sqlPrepare .= makeWhereStatement($garage_table, $garage, "garage");
$sqlPrepare .= makeWhereStatement($options_table, $options, "property_options");
$sqlPrepare .= makeWhereStatement($schools_table, $schools, "schools");
if (isset($_SESSION['city']) )
{
$sqlPrepare .= makeWhereStatement($city_table, $_SESSION['city'], "city");
}
if ($_SESSION['WhereStarted'] == true) //THIS WILL CAUSE THE SEARCH TO NOT SHOW ANY HOUSING THAT IS HIDDEN OR CLOSED
{
$sql_status = "WHERE status <> 'H' AND status <> 'C' AND status <> 'S' AND status <> 'D'";
}
else
{
$sql_status = "AND status <> 'H' AND status <> 'C' AND status <> 'S' AND status <> 'D'";
}
$_SESSION['Where'] = 'SELECT * FROM listings ' .$sqlPrepare ."".$sql_status;
$constructs = $_SESSION['Where'] . " ORDER BY listings.listing_id LIMIT 200";
$run = pg_query(db_connect(),$constructs);
$foundnum = pg_num_rows($run);
if ($foundnum >= 1)
{
header("Location: listing-matches.php");
ob_flush();
}
else
{
$error .= "No listings match the critera";
}
}
}
?>
<!-- about section start -->
<section class="content-body" id='search'>
<div class="max-width body-place search">
<h2 class="title">Listing Search</h2>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php //___________________________USED TO DISPLAY THE CITIES
$output = "";
$sql = 'SELECT * FROM '.$city_table;
$allOrNot = 0;
$city_start = true;
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
for($i = 0; $i < $records; $i++)
{
if (isBitSet($i, $city))
{
if ($city_start == true)
{
$output = "Location: ". pg_fetch_result($result, $i, "property");
}
else
{
$output .= ", ".pg_fetch_result($result, $i, "property");
}
$allOrNot += 1;
$city_start = false;
}
if ($allOrNot == $records || ($city == 0)) //IF ALL WERE PICKED OR NON WERE PICKED
{
$output = "Location: Durham Region";
}
}?>
<h2 style="text-align: center;"><?php echo $output; ?></h2>
<h3 style="text-align: center;"><?php echo $error; ?></h3>
<div>
# of bedrooms:<br/>
<?php
echo build_checkbox($bed_table, $beds);
?>
</div>
<div>
# of washrooms:<br/>
<?php
echo build_checkbox($wash_table, $wash);
?>
</div>
<div>
Open House?<br/>
<?php
echo build_checkbox($open_table, $open);
?>
</div>
<div>
House containing a finished basement?<br/>
<?php
echo build_checkbox($base_table, $base);
?>
</div>
<div>
Type of listing:
<br/>
<?php
echo build_checkbox($type_table, $purchase);
?>
</div>
<div>
Price for house:
<br/>
Minimum price: <input type="text" name="minimum" value="<?php echo $minimum;?>" /><br/>
Maximum Price: <input type="text" name="maximum" value="<?php echo $maximum;?>" />
</div>
<div>
Type of house:
<br/>
<?php
echo build_checkbox($property_table, $property_type);
?>
</div>
<div>
Garage Type:
<br/>
<?php
echo build_checkbox($garage_table, $garage);
?>
</div>
<div>
Property Options:<br/>
<?php
echo build_checkbox($options_table, $options);
?>
</div>
<div>
Near schools?<br/>
<?php
echo build_checkbox($schools_table, $schools);
?>
</div>
<input style="align: center" type="submit" name="submit" value="Submit" />
</form>
</div>
</section>
<?php include 'footer.php'; ?><file_sep><?php
/*
Group 13
September 29, 2016
WEBD3201
The Welcome Page
*/
$title = "Search Matches";
$date = "November 06, 2016";
$filename = "listing-matches.php";
$description = " It shows any matched information";
include("header.php");
?>
<br/>
<form action='listing-matches.php' method='GET'>
<center>
<h1>My Search Engine</h1>
<input type='text' size='90' name='search'><br/><br/>
<input type='submit' name='submit' value='Search source code' ><br/><br/><br/>
</center>
</form>
<?php
if (isset($_POST['formDoor']))
{
$aDoor = $_POST['formDoor'];
}
else
{
$aDoor = array();
}
?>
<form action="test1.php" method="post">
Which buildings do you want access to?<br />
<input type="checkbox" name="formDoor[]" value="A" <?php echo (in_array("A", $aDoor)) ? "checked": ""; ?>/>Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" <?php echo (in_array("B", $aDoor)) ? "checked": ""; ?>/>Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" <?php echo (in_array("C", $aDoor)) ? "checked": ""; ?>/>Carnegie Complex<br />
<input type="checkbox" name="formDoor[]" value="D" <?php echo (in_array("D", $aDoor)) ? "checked": ""; ?>/>Drake Commons<br />
<input type="checkbox" name="formDoor[]" value="E" <?php echo (in_array("E", $aDoor)) ? "checked": ""; ?>/>Elliot House
<input type="submit" name="submit" value="Submit" />
</form>
<?php
if(!isset($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($aDoor);
echo("You selected $N door(s): ");
for($i=0; $i < $N; $i++)
{
echo($aDoor[$i] . " ");
}
}
?>
<form action="test1.php" method="post">
<?php
//--------------------------------------------------------------------------WASH
$wash_table = 'washrooms';
echo "<BR>$wash_table <br>";
//If the page is load and there is a cookie set, it would choose the first option
if (isset($_COOKIE['washroom_search']) && !isset($_POST[$wash_table]))
{
$wash = unserialize($_COOKIE['washroom_search']);
}
else if (isset($_POST[$wash_table])) //Once the user presses submit button
{
$wash = $_POST[$wash_table];
setcookie("washroom_search", serialize($_POST[$wash_table]), time()+ COOKIE_LENGTH, "/");
}
else //If browser has neither cookies or options set up before
{
$wash = array();
}
echo build_checkbox($wash_table, $wash);
//--------------------------------------------------------------------------BED
$bed_table = 'bedrooms';
echo "<BR>$bed_table <br>";
//If the page is load and there is a cookie set, it would choose the first option
if (isset($_COOKIE['bed_search']) && !isset($_POST[$wash_table]))
{
$beds = unserialize($_COOKIE['bed_search']);
}
else if (isset($_POST[$bed_table])) //Once the user presses submit button
{
$beds = $_POST[$bed_table];
setcookie("bed_search", serialize($_POST[$bed_table]), time()+ COOKIE_LENGTH, "/");
}
else //If browser has neither cookies or options set up before
{
$beds = array();
}
echo build_checkbox($bed_table, $beds);
//--------------------------------------------------------------------------PROPERTY_Test
$propertyType_table = 'property_type';
echo "<BR>$propertyType_table <br>";
if (isset($_POST[$propertyType_table]))
{
$property_type = $_POST[$propertyType_table];
}
else
{
$property_type = array();
}
echo build_checkbox($propertyType_table, $property_type);
?>
<input type="submit" name="formSubmit" value="Submit" />
<?php
$sqlPrepare = ""; // main sequence code
$where = ""; // if it doesn't start with a where yet
$start = true; //used to check if there has already been a where statement
//----------------------------------------------------------------------------------------------------------------------WASHROOM
$sql = 'SELECT * FROM '.$wash_table;
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
for($i = 0; $i < $records; $i++)
{
if (in_array(pg_fetch_result($result, $i, "value"), $wash))
{
if (empty($where)) //Checks if where is empty
{
$where = "WHERE";
}
if (!isset($sql_bath)) //checks if sequence doesn't exist
{
$sql_bath = $where." (bathrooms = ". pg_fetch_result($result, $i, "value"). " ";
}
else if(isset($sql_bath)) //if it does exist
{
//$checked = (in_array(pg_fetch_result($result, $i, "value"), $wash)) ? pg_fetch_result($result, $i, "value"): "";
$sql_bath .= "OR bathrooms = ". pg_fetch_result($result, $i, "value"). " ";
}
$start = false; //
}
}
if (isset($sql_bath))// adds a end bracket after the sequence is finished
{
$sql_bath .= ") ";
echo "<br/>$sql_bath";
$sqlPrepare = $sql_bath; // main sequence to be used
//echo " <br/>SEQUENCE: $sqlPrepare";
}
//---------------------------------------------------------------------------------------------------------------------------------BEDS
$sql = 'SELECT * FROM '.$bed_table;
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
for($i = 0; $i < $records; $i++)
{
if (in_array(pg_fetch_result($result, $i, "value"), $beds))
{
if (empty($where) && ($start == true))//if the choices beforehand wasn't chosen, it would start a where
{
$where = "WHERE";
}
if (!isset($sql_beds) && ($start == true)) //Sets up the where in front of the criterias
{
$sql_beds = $where." (bedrooms = ". pg_fetch_result($result, $i, "value"). " ";
}
else if(!isset($sql_beds)) //Starts AND, if there options beforhand had WHERE started
{
$sql_beds = "AND (bedrooms = ". pg_fetch_result($result, $i, "value"). " ";
}
else if(isset($sql_beds)) //adds OR before the next criteria is entered
{
$sql_beds .= "OR bedrooms = ". pg_fetch_result($result, $i, "value"). " ";
}
$start = false;//Makes sure WHERE start once
}
}
if (isset($sql_beds))
{
$sql_beds .= ") ";
$sqlPrepare .= $sql_beds;
}
if(isset($sql_beds))
{
echo "<br/>$sql_beds";
}
//--------------------------------------------------------------------------------------------------------------------------property_type
$sql = 'SELECT * FROM '.$propertyType_table;
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
for($i = 0; $i < $records; $i++)
{
if (in_array(pg_fetch_result($result, $i, "value"), $property_type))
{
if (empty($where) && ($start == true))//if the choices beforehand wasn't chosen, it would start a where
{
$where = "WHERE";
}
if (!isset($sql_proType) && ($start == true)) //Sets up the where in front of the criterias
{
$sql_proType = $where." (property_type = ". pg_fetch_result($result, $i, "value"). " ";
}
else if(!isset($sql_proType)) //Starts AND, if there options beforhand had WHERE started
{
$sql_proType = "AND (property_type = ". pg_fetch_result($result, $i, "value"). " ";
}
else if(isset($sql_proType)) //adds OR before the next criteria is entered
{
$sql_proType .= "OR property_type = ". pg_fetch_result($result, $i, "value"). " ";
}
$start = false;//Makes sure WHERE start once
}
}
if (isset($sql_proType))
{
$sql_proType .= ") ";
$sqlPrepare .= $sql_proType;
}
if(isset($sql_proType))
{
echo "<br/>$sql_proType";
}
//echo "<BR><BR> $sqlPrepare" ;
if (isset($sql_proType) || isset($sql_beds) || isset($sql_bath))
{
$_SESSION['tttt'] = 'SELECT * FROM listings ' .$sqlPrepare;
echo "<BR><BR> ". $_SESSION['tttt'];
/* header("refresh:5;url=listing-matches.php");
ob_flush(); */
}
?>
</form>
<br/>
<?php include 'footer.php'; ?><file_sep><?php
/*
Group 13
November 10, 2016
WEBD3201
The list match result page
*/
$title = "Search Matches";
$date = "November 06, 2016";
$filename = "listing-matches.php";
$description = " It shows any matched information";
include("header.php");
?>
<br/>
<!-- about section start -->
<section class="content-body result" id='result'>
<div class="max-width body-place">
<h2 class="title">Search Result</h2>
<?php
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$_SESSION['previousPage'] = $actual_link;
//http://www.findsourcecode.com/php/pagination-in-search-engine/
if (isset($_SESSION['Where'])) //_________________checks if statement was created
{
$search = $_SESSION['Where'];
}
else
{
echo "You will be redirected to be able to the search page";
header("refresh:5;url=listing-cities.php");
}
if (isset($_GET ['submit']))
{
$button = $_GET['submit'];
$search = $_SESSION['Where'];
}
if(strlen($search)<=1)
echo "Search term too short";
else
{
$search_exploded = explode (" ", $search);
$x = "";
$construct = "";
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="title LIKE '%$search_each%'";
else
$construct .="AND title LIKE '%$search_each%'";
}
//USED TO MAKE THE NUMBER OF PAGINATE
$constructs = $_SESSION['Where'] . " ORDER BY listings.listing_id LIMIT 200";/*"SELECT * FROM listings
WHERE 1 = 1 AND (listings.city = 4 OR listings.city = 8 OR listings.city = 64)
AND (listings.bedrooms = 16 OR listings.bedrooms = 32)
AND (listings.property_type = 2 OR listings.property_type = 8 OR listings.property_type = 128)
AND listings.price >= 125000 AND listings.price <= 900000
AND listings.status = 'O' ORDER BY listings.listing_id";*/
//echo $constructs;
$run = pg_query(db_connect(),$constructs);
$foundnum = pg_num_rows($run);
if ($foundnum==0) // IF no matches are found
{
echo "Sorry, there are no matching result for your critera<br/>";
}
else if ($foundnum==1) //REDIRECTS THE USER TO THE LISTING VIEW PAGE
{
$listing_id = pg_fetch_result($run, 0, "listing_id");
echo "You found one";
header("Location: listing-view.php?submit=Search+source+code&listing_id=$listing_id");
}
else
{
//Shows the number of results match the criteria
echo "$foundnum results found !<p>";
//sets the number of houses per pages
$per_page = PAGE_LIMIT;
$start = isset($_GET['start']) ? $_GET['start']: 0;
//find the appropriate number of pages needed to display the page
$max_pages = ceil($foundnum / $per_page);
//Page starts at the first records
if(!$start){
$start=0;
}
//Set up the query
$getquery = pg_query(db_connect(), $_SESSION['Where']. " ORDER BY listings.listing_id DESC LIMIT $per_page OFFSET $start");
//echo $_SESSION['Where']. " ORDER BY listings.listing_id DESC LIMIT $per_page OFFSET $start <br>";
//_______________________________________________________________________________________________________CREATES THE TABLE
while($runrows = pg_fetch_assoc($getquery))
{
$listing_id = $runrows['listing_id'];
$user_id = $runrows['user_id'];
$city = $runrows['city'];
$headline = $runrows['headline'];
$description = $runrows['description'];
$bed = $runrows['bedrooms'];
$bath = $runrows['bathrooms'];
$price = $runrows['price'];
$property = $runrows['property_type'];
$garage = $runrows['garage'];
$schools = $runrows['schools'];
$image = $runrows['images'];
echo "\n<div class=\"row-info\">";
echo "\n<div class=\"column left\">";//IMAGE LOAD SECTION
if (file_exists("./listing/$listing_id/".$listing_id."_".$image.".jpg"))
{
echo "<img src=\"./listing/$listing_id/".$listing_id."_".$image.".jpg\" alt=\"House Image\" width=\"200px\"/>";
}
else
{
echo "<img src=\"images/notFound.jpg\" alt=\"Image Not Found\" width=\"300px\" />";
}
echo "\n</div>";
echo "\n<div class=\"column right\">";
//THE INFORMATION OF THE HOUSE
echo "<a class=\"homelist\" href=\"listing-view.php?submit=Search+source+code&listing_id=$listing_id\" >$headline </a>
<br/>LOCATION: ".get_property('cities',$city)."
<br/>PRICE: $". number_format($price,2) . " ";
echo "\n</div>";
echo "\n</div>";
}
//Pagination Starts
echo "<center>";
$prev = $start - $per_page;
$next = $start + $per_page;
$adjacents = 3;
$last = $max_pages - 1;
if($max_pages > 1)
{
//previous button
if (!($start<=0))
echo " <a href='listing-matches.php?submit=Search+source+code&start=$prev'>Prev</a> ";
//In the first 6 pages, it doesn't skip
if ($max_pages < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='listing-matches.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='listing-matches.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
elseif($max_pages > 5 + ($adjacents * 2)) //enough pages to hide some but the first two and the next 3 pages
{
//close to beginning; only hide later pages
if(($start/$per_page) < 1 + ($adjacents * 2))
{
$i = 0;
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($i == $start){
echo " <a href='listing-matches.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='listing-matches.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//in middle; hide some front and some back
elseif($max_pages - ($adjacents * 2) > ($start / $per_page) && ($start / $per_page) > ($adjacents * 2))
{
echo " <a href='listing-matches.php?submit=Search+source+code&start=0'>1</a> ";
echo " <a href='listing-matches.php?submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start/$per_page)+1; $counter < ($start / $per_page) + $adjacents + 2; $counter++)
{
if ($i == $start){
echo " <a href='listing-matches.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='listing-matches.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//close to end; only hide early pages
else
{
echo " <a href='listing-matches.php?submit=Search+source+code&start=0'>1</a> ";
echo " <a href='listing-matches.php?submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start / $per_page) + 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='listing-matches.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='listing-matches.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
}
//next button
if (!($start >=$foundnum-$per_page))
echo " <a href='listing-matches.php?submit=Search+source+code&start=$next'>Next</a> ";
}
echo "</center>";
}
}
?>
</div>
</section>
<br/>
<?php include 'footer.php'; ?><file_sep><?php
/*
Group_13
September 29, 2016
WEBD3201
Login page
*/
$title = "Login";
$date = "September 29, 2016";
$filename = "login.php";
$description = "The login page ";
include("header.php");
?>
<?php
//empty out error and result regardless of method that got you here
$error = "";
$output = (isset($_SESSION['message']))? $_SESSION['message']: "";
if (isset($_SESSION['message']) )
{
unset($_SESSION['message']);
}
if($_SERVER["REQUEST_METHOD"] == "GET")
{
//default mode when the page loads the first time
//can be used to make decisions and initialize variables
$id = "";
$pass = "";
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
//the page got here from submitting the form, let's try to process
$id = trim($_POST["id"]); //the name of the input box on the form, white-space removed
$pass = trim($_POST["pass"]); //the name of the input box on the form, white-space removed
//Converts the password into a hash
$hashedPass = hash("md5", $pass);
$result = pg_execute(db_connect(),"Log_In_query",array($id,$hashedPass));
$records = pg_num_rows($result);
//-------------------------------------------------------------------------------------------PASSES
//Checks if both id and pass is correct
if ($records == 1)
{
pg_execute(db_connect(),"UpdateUserDate",array($id));
//Sets users cookie
$cookie_name = "user";
$cookie_value = $id;
setcookie("user",$cookie_value, time() + COOKIE_LENGTH, "/"); // 86400 = 1 day
//Redirects to welcome page
$_SESSION['loggedin'] = true;
//-----------------------------------------------------------USERS TABLE SESSION VARIABLES
$_SESSION['username'] = $id;
$_SESSION['password'] = $<PASSWORD>;
$_SESSION['user_type'] = pg_fetch_result($result, 0, "user_type");
$_SESSION['email'] = pg_fetch_result($result, 0, "email_address");
$_SESSION['enrol'] = pg_fetch_result($result, 0, "enrol_date");
$_SESSION['last_access'] = pg_fetch_result($result, 0, "last_access");
//-----------------------------------------------------------PEOPLE TABLE SESSION VARIABLES
$result = pg_execute(db_connect(), "Get_Personal",array($id));
$_SESSION['salutation'] = pg_fetch_result($result, 0, "salutation");
$_SESSION['first_name'] = pg_fetch_result($result, 0, "first_name");
$_SESSION['last_name'] = pg_fetch_result($result, 0, "last_name");
$_SESSION['street_address_1'] = pg_fetch_result($result, 0, "street_address_1");
$_SESSION['street_address_2'] = pg_fetch_result($result, 0, "street_address_2");
$_SESSION['city'] = pg_fetch_result($result, 0, "city");
$_SESSION['province'] = pg_fetch_result($result, 0, "province");
$_SESSION['postal_code'] = pg_fetch_result($result, 0, "postal_code");
$_SESSION['primary_phone'] = pg_fetch_result($result, 0, "primary_phone_number");
$_SESSION['secondary_phone'] = pg_fetch_result($result, 0, "secondary_phone_number");
$_SESSION['fax'] = pg_fetch_result($result, 0, "fax_number");
$_SESSION['contact_method'] = pg_fetch_result($result, 0, "preferred_contact_method");
//------------------------------------------------------------------------------------------------------------------------------------AGENT
if ($_SESSION['user_type'] == GET_AGENT)
{
header("refresh:5;url=dashboard.php");
echo "<br/>Successful logged-in as ".$id.", you will be redirected to your Dashboard page";
ob_flush();
}
//------------------------------------------------------------------------------------------------------------------------------------USER
else if($_SESSION['user_type'] == GET_USER)
{
header("refresh:5;url=welcome.php");
echo "<br/>Successful logged-in as ".$id.", you will be redirected to your welcome page";
ob_flush();
}
//------------------------------------------------------------------------------------------------------------------------------------ADMIN
else if($_SESSION['user_type'] == GET_ADMIN)
{
header("refresh:5;url=admin.php");
echo "<br/>Successful logged-in as ".$id.", you will be redirected to your admin page";
ob_flush();
}
//------------------------------------------------------------------------------------------------------------------------------------PENDING AGENT
else if($_SESSION['user_type'] == GET_PENDING)
{
echo "<br/>Successful logged-in as ".$id.", your account is still pending to be approved";
session_destroy();
}
//------------------------------------------------------------------------------------------------------------------------------------DISABLED
else if($_SESSION['user_type'] == GET_DISABLED)
{
echo "<br/>Successful logged-in as ".$id.", your account has been suspended";
echo "<br/>You will be redirected to our Acceptable User Policy page";
session_destroy();
header("refresh:5;url=aup.php");
}
}
else //-------------------------------------------------------------------------------USER AND PASSWORD NOT FOUND
{
if (is_user_id($id) == true)
{
//If user name is found at least
$error = "Incorrect Password";
$pass = "";
}
else
{
$error = "Login/password not found in the database";
$id = "";
$pass = "";
}
}
}
?>
<h1>Realtor Login Page</h1>
<hr/>
<p>If your a realtor and don't have an account, please go to the <a href="./register.php">registration</a> page on the top bar.
<br/>
</p>
<h2 style="text-align: center;"><?php echo $output; ?></h2>
<h3 style="text-align: center;"><?php echo $error; ?></h3>
<p style="text-align: center;">Enter your login ID and password to connect to this system</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table style="border: none;
background-color: #e5f2ff;
width: auto;
text-align: center;
margin-left: auto;
margin-right: auto;" cellspacing="15">
<tr>
<td>
Login ID:
</td>
<td><input type="text" name="id" value="<?php echo $id; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td>Password:
</td>
<td><input type="password" name="pass" value="<?php echo $pass; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Log In" /></td>
</tr>
</table>
</form>
<br/>
<?php include 'footer.php'; ?>
<file_sep><?php
/*
Group 13
September 29, 2016
WEBD3201
The Welcome Page
*/
$title = "Welcome";
$date = "September 29, 2016";
$filename = "index.php";
$description = " A page that welcomes the agent";
include("header.php");
?>
<?php
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$_SESSION['previousPage'] = $actual_link;
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['user_type'] == GET_ADMIN)
{
echo "<section class=\"content-body result\" id='result'>
<div class=\"max-width body-place\">
<h2 class=\"title\">Welcome to the Admin's area, " . $_SESSION['username'] . "!</h2>
<div class=\"row-info\">";
echo "\n<br/>Password: ".$_SESSION['password']." User Type: ".$_SESSION['user_type']."";
echo "\n<br/>Email: " .$_SESSION['email']. " Enrolled Date: ". $_SESSION['enrol']."";
echo "\n<br/> Last Access: ".$_SESSION['last_access']."";
echo "\n<br/> Personal Information";
echo "\n<br/> Salutation: ".$_SESSION['salutation']."";
echo "\n<br/> First Name: ".$_SESSION['first_name']."";
echo "\n<br/> Last Name: ".$_SESSION['last_name']."";
echo "\n<br/> 1st Street: ".$_SESSION['street_address_1']."";
echo "\n<br/> 2nd Street: ".$_SESSION['street_address_2']."";
echo "\n<br/> City: ".$_SESSION['city']."";
echo "\n<br/> Provinces: ".$_SESSION['province']."";
echo "\n<br/> Primary Phone: ". $_SESSION['primary_phone']."";
echo "\n<br/> Secondary Phone: ". $_SESSION['secondary_phone']."";
echo "\n<br/> Fax Number: ". $_SESSION['fax']."";
echo "\n<br/> Preferred Contact Method: ".$_SESSION['contact_method']."";
//When admin accepts agent is clicked
if (isset($_GET['Accept_user']))
{
$findUser = "SELECT * FROM users WHERE user_id='".$_GET['Accept_user']."' ";
$userFound = pg_query(db_connect(), $findUser);
//Checks if user is stil pending, no backdoor system to update any user to change a user
if (pg_fetch_result($userFound, 0, "user_type") == GET_PENDING)
{
$updateAgent = "UPDATE users SET user_type='".GET_AGENT."' WHERE user_id = '".$_GET['Accept_user']."'";
pg_query(db_connect(), $updateAgent);
}
header("Location: admin.php");
}
//When admin disables pending agent
if (isset($_GET['Disable_user']))
{
$findUser = "SELECT * FROM users WHERE user_id='".$_GET['Disable_user']."' ";
$userFound = pg_query(db_connect(), $findUser);
//Checks if user is stil pending, no backdoor system to update any user to change a user
if (pg_fetch_result($userFound, 0, "user_type") == GET_PENDING)
{
$updateAgent = "UPDATE users SET user_type='".GET_DISABLED."' WHERE user_id = '".$_GET['Disable_user']."'";
pg_query(db_connect(), $updateAgent);
}
header("Location: admin.php");
}
//When admin disables a spammy reporter
if (isset($_GET['Disable_reporter']))
{
$findUser = "SELECT * FROM users WHERE user_id='".$_GET['Disable_reporter']."' ";
$userFound = pg_query(db_connect(), $findUser);
//Checks if user is stil pending, no backdoor system to update any user to change a user
if (pg_fetch_result($userFound, 0, "user_type") != GET_DISABLED)
{
$updateAgent = "UPDATE users SET user_type='".GET_DISABLED."' WHERE user_id = '".$_GET['Disable_reporter']."'";
pg_query(db_connect(), $updateAgent);
}
//Removes their favourites
$getFavourites = pg_query(db_connect(), "SELECT * FROM reports JOIN users ON reports.user_id = users.user_id JOIN people ON users.user_id = people.user_id WHERE reports.user_id='".$_GET['Disable_reporter']."' LIMIT 200");
while($runrows = pg_fetch_assoc($getFavourites))
{
$user_id = $runrows['user_id'];
$listing_id = $runrows['listing_id'];
$date = $runrows['reported_on'];
$firstNameReport = $runrows['first_name'];
$lastNameReport = $runrows['last_name'];
$insertSQL = "DELETE FROM favourites WHERE user_id ='".$_GET['Disable_reporter']."' AND listing_id ='".$listing_id."';";
pg_query(db_connect(), $insertSQL);
}
$getReports = pg_query(db_connect(), "SELECT * FROM reports JOIN users ON reports.user_id = users.user_id JOIN people ON users.user_id = people.user_id WHERE reports.user_id='".$_GET['Disable_reporter']."' LIMIT 200");
while($runrows = pg_fetch_assoc($getReports))
{
$user_id = $runrows['user_id'];
$listing_id = $runrows['listing_id'];
$date = $runrows['reported_on'];
$firstNameReport = $runrows['first_name'];
$lastNameReport = $runrows['last_name'];
$close = "UPDATE reports SET status='".CLOSED."' WHERE user_id='". $_GET['Disable_reporter']."'";
pg_query(db_connect(), $close);
}
header("Location: admin.php");
}
//SQL code to get users that are pending to be agents
$sql = "select * from users join people on users.user_id = people.user_id where users.user_type='P' ORDER BY users.user_id DESC";
$result = pg_query(db_connect(), $sql ." LIMIT 200 ");
$records = pg_num_rows($result);
echo "<br/><br/>";
$search = $sql;
$search_exploded = explode (" ", $search);
$x = "";
$construct = $sql;
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="title LIKE '%$search_each%'";
else
$construct .="AND title LIKE '%$search_each%'";
}
//USED TO MAKE THE NUMBER OF PAGINATE
$constructs = $sql;/*"SELECT * FROM listings
WHERE 1 = 1 AND (listings.city = 4 OR listings.city = 8 OR listings.city = 64)
AND (listings.bedrooms = 16 OR listings.bedrooms = 32)
AND (listings.property_type = 2 OR listings.property_type = 8 OR listings.property_type = 128)
AND listings.price >= 125000 AND listings.price <= 900000
AND listings.status = 'O' ORDER BY listings.listing_id";*/
//echo $constructs;
$run = pg_query(db_connect(),$constructs);
$foundnum = pg_num_rows($run);
//Shows the number of results match the criteria
echo "<h2 align=\"center\">Show Pending Agents </h2>";
//echo "<p>$foundnum results found !<p>";
//Set up the query
$getquery = pg_query(db_connect(), $sql. "");
//echo $_SESSION['Where']. " ORDER BY listings.listing_id DESC LIMIT $per_page OFFSET $start <br>";
echo "<form action=\"$actual_link\" method=\"post\">";
//_______________________________________________________________________________________________________CREATES THE DISABLED TABLE
echo "\n<table border=\"0\">";
$i=0;
if ($i == 0)
{
echo "<tr><th>User ID</th><th>Full Name</th><th>Accept User</th><th>Disable User</th></tr>";
}
while($runrows = pg_fetch_assoc($getquery))
{
$user_id = $runrows['user_id'];
$firstName = $runrows['first_name'];
$lastName = $runrows['last_name'];
$i +=1;
echo "\n<tr><td> ";
echo "$user_id";
echo "\n</td>";
echo "\n<td>";
echo "<br/>$firstName $lastName ";
echo "\n</td> \n\t\t<td> <a class=\"homelist\" href=\"admin.php?Accept_user=$user_id\" > Accept </a> </td>";
echo "<td> <a class=\"homelist\" href=\"admin.php?Disable_user=$user_id\" > Disable </a> </td> </tr>";
echo "\n<tr><td colspan=\"4\">";
echo "\n\t<hr/>";
echo "\n</td></tr>";
}
echo "\n</table>";
//Shows the number of results match the criteria
echo "<br/><h2 align=\"center\">Show Reported Lists </h2>";
//echo "<p>$foundnum results found !<p>";
//Set up the query
$getReports = pg_query(db_connect(), "SELECT * FROM reports JOIN users ON reports.user_id = users.user_id JOIN people ON users.user_id = people.user_id WHERE status='".OPEN."' ORDER BY reports.reported_on");
//_______________________________________________________________________________________________________CREATES THE REPORTED TABLE
echo "\n<table border=\"0\">";
$i=0;
if ($i == 0)
{
echo "<tr><th>Time Reported</th><th>Listing ID</th><th>User ID</th><th>Reporter's Name</th><th>Visit Listing</th><th>Disable Reporter</th></tr>";
}
while($runrows = pg_fetch_assoc($getReports))
{
$user_id = $runrows['user_id'];
$listing_id = $runrows['listing_id'];
$date = $runrows['reported_on'];
$firstNameReport = $runrows['first_name'];
$lastNameReport = $runrows['last_name'];
$i +=1;
echo "\n<tr><td> ";
echo " $date";
echo "\n</td>";
echo "\n<td>";
echo "<br/>$listing_id </td> <td>$user_id </td><td> $firstNameReport $lastNameReport ";
echo "\n</td> \n\t\t<td><a class=\"homelist\" href=\"listing-view.php?submit=Search+source+code&listing_id=$listing_id\" > Visit </a> </td>";
echo "<td> <a class=\"homelist\" href=\"admin.php?Disable_reporter=$user_id\" > Disable </a> </td> </tr>";
echo "\n<tr><td colspan=\"6\">";
echo "\n\t<hr/>";
echo "\n</td></tr>";
}
echo "\n</table>";
echo "</form>";
echo "</div>
</div>
</section>";
} else
{
header("Location: /");
}
?>
<?php include 'footer.php'; ?>
<file_sep><?php
/*
Group 13
September 29, 2016
WEBD3201
The search result page
*/
$title = "Search Result";
$date = "September 29, 2016";
$filename = "index.php";
$description = "The search result page ";
include("header.php");
?>
<h1> Listing Gallery </h1>
<hr/>
<table style="width:50%" border="1px solid black">
<tr>
<th>Listing Image</th>
<th>Listing Description</th>
</tr>
<tr>
<th rowspan="2"><img src="Houses/brampton_house.jpg" alt="Oshawa House" width="300px" height="200px"/>
</th>
<td align="left" valign="top"><ul>
<li>4 Washrooms</li>
<li>5 Bedrooms</li>
<li>Near a school</li>
</ul>
<form action="listing-display1.php">
<p>
<input type="submit" name="submit" value="Full listing description"/></p>
</form>
</td>
</tr>
<tr>
<td align="left" valign="top"><ul>
<li>Location: Oshawa</li>
<li>Price: $1,000,000</li>
</ul></td>
</tr>
<tr>
<th rowspan="2"><img src="Houses/bolmanville.jpg" alt="Oshawa House" width="300px" height="200px"/>
</th>
<td align="left" valign="top"><ul>
<li>Finished Basement</li>
<li>3 Bedrooms</li>
<li>Status: Open</li>
</ul>
<form action="listing-display2.php">
<p>
<input type="submit" name="submit" value="Full listing description"/></p>
</form>
</td>
</tr>
<tr>
<td align="left" valign="top"><ul>
<li>Location: Bowmanville</li>
<li>Price: $600,000</li>
</ul></td>
</tr>
<tr>
<th rowspan="2"><img src="Houses/ajax.jpg" alt="Oshawa House" width="300px" height="200px"/>
</th>
<td align="left" valign="top"><ul>
<li>3 Garage Doors</li>
<li>Open House</li>
<li>Near two schools</li>
</ul>
<form action="listing-display3.php">
<p>
<input type="submit" name="submit" value="Full listing description"/></p>
</form>
</td>
</tr>
<tr>
<td align="left" valign="top"><ul>
<li>Location: Ajax</li>
<li>Price: $1,700,000</li>
</ul></td>
</tr>
<tr>
<th rowspan="2"><img src="Houses/pickering.JPG" alt="Pickering House" width="300px" height="200px"/>
</th>
<td align="left" valign="top"><ul>
<li>Duplex</li>
<li>For Rent or Sale</li>
<li>2 washrooms</li>
</ul>
<form action="listing-display4.php">
<p>
<input type="submit" name="submit" value="Full listing description"/></p>
</form>
</td>
</tr>
<tr>
<td align="left" valign="top"><ul>
<li>Location: Pickering</li>
<li>Price: $300,000</li>
</ul></td>
</tr>
</table>
<?php include 'footer.php'; ?><file_sep>--Group 13
--property_type.sql
--October 19, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS property_type;
--Creates the table again
CREATE TABLE property_type(
value INT PRIMARY KEY,
property VARCHAR(30) NOT NULL
);
--Inserts rows inside the table
INSERT INTO property_type (value, property) VALUES (1, 'House');
INSERT INTO property_type (value, property) VALUES (2, 'Semi-Detached');
INSERT INTO property_type (value, property) VALUES (4, 'Condo');
INSERT INTO property_type (value, property) VALUES (8, 'Townhouse');<file_sep>
<div id="footer">
<!-- start of footer -->
<a href="privacy_policy.php">Privacy Policy</a>
<a href="aup.php">Acceptance Use Policy</a>
<a href="http://validator.w3.org/check?uri=referer">
<img style="width:88px;
height:31px;"
src="http://www.w3.org/Icons/valid-xhtml10"
alt="Valid XHTML 1.0 Strict" />
</a>
<a href="http://jigsaw.w3.org/css-validator/check/referer">
<img style="width:88px;
height:31px;"
src="http://jigsaw.w3.org/css-validator/images/vcss"
alt="Valid CSS!" />
</a>
<?php displayCopyright(); ?>
<!-- end of footer -->
</div>
</div>
</div>
</body>
</html><file_sep>--Group 13
--garage_type.sql
--October 19, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS garage_type;
--Creates the table again
CREATE TABLE garage_type(
value INT PRIMARY KEY,
property VARCHAR(30) NOT NULL
);
--Inserts rows inside the table
INSERT INTO garage_type (value, property) VALUES (1, 'No Garage');
INSERT INTO garage_type (value, property) VALUES (2, 'One Garage');
INSERT INTO garage_type (value, property) VALUES (4, 'Double Garage');
INSERT INTO garage_type (value, property) VALUES (8, 'Three Garage or more');<file_sep>--Group 13
--finished_basement.sql
--October 19, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS finished_basement;
--Creates the table again
CREATE TABLE finished_basement(
value INT PRIMARY KEY,
property VARCHAR(30) NOT NULL
);
--Inserts rows inside the table
INSERT INTO finished_basement (value, property) VALUES (1, 'Yes');
INSERT INTO finished_basement (value, property) VALUES (2, 'No');
<file_sep>--Group 13
--open_house.sql
--October 19, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS open_house;
--Creates the table again
CREATE TABLE open_house(
value INT PRIMARY KEY,
property VARCHAR(30) NOT NULL
);
--Inserts rows inside the table
INSERT INTO open_house (value, property) VALUES (1, 'Yes');
INSERT INTO open_house (value, property) VALUES (2, 'No');<file_sep><?php
/*
Group_13
November 21, 2016
WEBD3201
Update page
*/
$title = "Update";
$date = "November 21, 2016";
$filename = "Update.php";
$description = "The update page to update a users information";
include("header.php");
?>
<?php
$error = "";
$output = "";
if (!isset($_SESSION['loggedin']) )
{
header("Location: login.php");
}
if($_SERVER["REQUEST_METHOD"] == "GET")
{
//default mode when the page loads the first time
//can be used to make decisions and initialize variables
//User Table Fields
$first = $_SESSION['first_name'] ;
$last = $_SESSION['last_name'] ;
$email = $_SESSION['email'];
//People Table Fields
$salutation = $_SESSION['salutation'];
$provinces = $_SESSION['province'] ;
$street = $_SESSION['street_address_1'] ;
$secondStreet = $_SESSION['street_address_2'] ;
$city = $_SESSION['city'] ;
$postal = $_SESSION['postal_code'];
$phone = $_SESSION['primary_phone'] ;
$secondPhone = $_SESSION['secondary_phone'] ;
$fax = $_SESSION['fax'] ;
$selected_method = $_SESSION['contact_method'];
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
//the page got here from submitting the form, let's try to process
$first = trim($_POST["first"]); //the name of the input box on the form, white-space removed
$last = trim($_POST["last"]); //the name of the input box on the form, white-space removed
$email = trim($_POST["email"]); //the name of the input box on the form, white-space removed
//Peoples variables
$salutation = trim($_POST['salutation']);
$street = trim($_POST['street']);
$secondStreet = trim($_POST['2ndStreet']);
$city = trim($_POST['city']);
$provinces = trim($_POST['provinces']);
$postal = trim($_POST['postal']);
$phone = trim($_POST['phone']);
$secondPhone = trim($_POST['2ndPhone']);
$fax = trim($_POST['fax']);
$selected_method = "";
//----------------------------------------------------------------------------------------------FIRST NAME
if(!isset($first) || $first == "")
{
//means the user did not enter anything
$error .= "First Name input is empty. <br/>";
}
else if (trim(strlen($first)) > MAX_FIRST_NAME_LENGTH)
{
$error .= "First Name input is more than the ".MAX_FIRST_NAME_LENGTH." limit<br/>";
}
else if (is_numeric($first))
{
$error .= "First Name (".$first.") cannot be a numeric<br/>";
$first = "";
}
//----------------------------------------------------------------------------------------------LAST NAME
if(!isset($last) || $last == "")
{
//means the user did not enter anything
$error .= "Last Name is empty. <br/>";
}
else if (trim(strlen($last)) > MAX_LAST_NAME_LENGTH)
{
$error .= "Last Name input is more than the ".MAX_LAST_NAME_LENGTH." limit <br/>";
}
else if (is_numeric($last))
{
$error .= "Last Name (".$last.") cannot be a numeric<br/>";
$last = "";
}
//----------------------------------------------------------------------------------------------EMAIL
if(!isset($email) || $email == "")
{
//means the user did not enter anything
$error .= "Email is empty. <br/>";
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .= "Email (".$email.") is not format properly (<EMAIL>) <br/>";
$email = "";
}
//----------------------------------------------------------------------------------------------POSTAL CODE
if(!isset($postal) || !($postal == ""))//if values are entered
{
//means the user did not enter anything
if (trim(strlen($postal)) > MAXIMUM_POSTAL_LENGTH)
{
$error .= "Postal Code cannot be more than ".MAXIMUM_POSTAL_LENGTH." characters <br/>";
}
else if (is_valid_postal_code($postal))
{
$error .= "Postal Code (".$postal.") is not a valid Postal Code<br/>";
$postal = "";
}
}
//----------------------------------------------------------------------------------------------PHONE NUMBER
if ( !isset($phone) || $phone == "")
{
if(!preg_match('/^[0-9]{3}[0-9]{3}[0-9]{4}$/', $phone))
{
$error .= "\n Phone Number have to have 10 numbers<br/>";
}
else if (substr($phone, 0,3) < MINIMUM_PHONE_LENGTH)
{
$error .= "\n Phone number area code must be ".MINIMUM_PHONE_LENGTH." or more<br/>";
}
else if (substr($phone, 3,3) < MINIMUM_PHONE_LENGTH)
{
$error .= "\n Phone number exchange code must be ".MINIMUM_PHONE_LENGTH." or more<br/>";
}
}
//----------------------------------------------------------------------------------------------SECOND PHONE NUMBER
if (!isset($secondPhone) || !$secondPhone == "")
{
if(!preg_match('/^[0-9]{3}[0-9]{3}[0-9]{4}$/', $secondPhone))
{
$error .= "\n Phone Number have to have 10 numbers<br/>";
}
else if (substr($secondPhone, 0,3) < MINIMUM_PHONE_LENGTH)
{
$error .= "\n Phone number area code must be ".MINIMUM_PHONE_LENGTH." or more<br/>";
}
else if (substr($secondPhone, 3,3) < MINIMUM_PHONE_LENGTH)
{
$error .= "\n Phone number exchange code must be ".MINIMUM_PHONE_LENGTH." or more<br/>";
}
}
//----------------------------------------------------------------------------------------------FAX NUMBER
if (!isset($fax) || !$fax == "")
{
if(!preg_match('/^[0-9]{3}[0-9]{3}[0-9]{4}$/', $fax))
{
$error .= "\n Phone Number have to have 10 numbers<br/>";
}
else if (substr($fax, 0,3) < MINIMUM_PHONE_LENGTH)
{
$error .= "\n Phone number area code must be ".MINIMUM_PHONE_LENGTH." or more<br/>";
}
else if (substr($fax, 3,3) < MINIMUM_PHONE_LENGTH)
{
$error .= "\n Phone number exchange code must be ".MINIMUM_PHONE_LENGTH." or more<br/>";
}
}
//----------------------------------------------------------------------------------------------CONTACT METHOD
if (isset($_POST['submit']) && isset($_POST['contact_method']))//Sets the variable
{
$selected_method = $_POST['contact_method'];
}
//if error is an empty string
if($error == "")
{
$output = "Successful Updated information";
$_SESSION['first_name'] = $first ;
$_SESSION['last_name'] = $last ;
$_SESSION['email'] = $email;
//People Table Fields
$_SESSION['salutation'] = $salutation;
$_SESSION['province'] = $provinces ;
$_SESSION['street_address_1'] = $street;
$_SESSION['street_address_2'] = $secondStreet ;
$_SESSION['city'] = $city ;
$_SESSION['postal_code'] = $postal;
$_SESSION['primary_phone'] = $phone;
$_SESSION['secondary_phone'] =$secondPhone ;
$_SESSION['fax'] = $fax;
$_SESSION['contact_method'] = $selected_method;
pg_execute(db_connect(),"update_users",array($email,$_SESSION['username']) );
pg_execute(db_connect(),"update_people",array($salutation,$first,$last,$street,$secondStreet,$city,$provinces,$postal,$phone,$secondPhone,$fax,$selected_method, $_SESSION['username']) );
}
}
?>
<!-- form section start -->
<section class="content-body" id='formSetup'>
<div class="max-width body-place">
<h2 class="title">Update Information Page</h2>
<h2 style="text-align: center;"><?php echo $output; ?></h2>
<h3 style="text-align: center;"><?php echo $error; ?></h3>
<h3 style="text-align: center;">Fill in fields you wish to update</h3>
<h4 style="text-align: center;"> * cannot be empty</h4>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<div class="input-field">
<input type="text" name="email" value="<?php echo $email; ?>" size="30" required/>
<label>Email Address*</label>
</div>
<div class="input-field">
<input type="text" name="first" value="<?php echo $first; ?>" size="30" required/>
<label>First Name*</label>
</div>
<div class="input-field">
<input type="text" name="last" value="<?php echo $last; ?>" size="30" required />
<label>Last Name*</label>
</div>
<div class="otherForm">
<?php
$table = 'salutation';
echo build_simple_dropdown($table, $salutation);
?>
<label>Salutation</label>
</div>
<div class="input-field">
<input type="text" name="street" value="<?php echo $street; ?>" size="30" />
<label>Street Address 1</label>
</div>
<div class="input-field">
<input type="text" name="2ndStreet" value="<?php echo $secondStreet; ?>" size="30" />
<label>Street Address 2</label>
</div>
<div class="input-field">
<input type="text" name="city" value="<?php echo $city; ?>" size="30" />
<label>City</label>
</div>
<div class="otherForm">
<?php
$table = 'provinces';
echo build_simple_dropdown($table, $provinces);
?>
<label>Province:</label>
</div>
<div class="input-field">
<input type="text" name="postal" value="<?php echo $postal; ?>" size="30" />
<label>Postal Code</label>
</div>
<div class="input-field">
<input type="text" name="phone" value="<?php echo $phone; ?>" size="30" required/>
<label>Phone Number*</label>
</div>
<div class="input-field">
<input type="text" name="2ndPhone" value="<?php echo $secondPhone; ?>" size="30" />
<label>Phone Number 2</label>
</div>
<div class="input-field">
<input type="text" name="fax" value="<?php echo $fax; ?>" size="30" />
<label>Fax Number</label>
</div>
<div class="radioForm">
<div>
Preferred contact method:
</div>
<?php
$table = 'contact_method';
echo build_radio($table,$selected_method)
?>
</div>
<input type="submit" name="submit" value="Edit Profile" />
</form>
</div>
</section>
<?php include 'footer.php'; ?>
<file_sep><?php
require("./includes/constants.php");
require("./includes/functions.php");
require("./includes/db.php");
//http://www.findsourcecode.com/php/pagination-in-search-engine/
$button = $_GET ['submit'];
$search = $_GET ['search'];
if(strlen($search)<=1)
echo "Search term too short";
else
{
echo "You searched for <b>$search</b> <hr size='1'></br>";
$search_exploded = explode (" ", $search);
$x = "";
$construct = "";
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="title LIKE '%$search_each%'";
else
$construct .="AND title LIKE '%$search_each%'";
}
$constructs = "SELECT * FROM listings";
$run = pg_query(db_connect(),$constructs);
$foundnum = pg_num_rows($run);
if ($foundnum==0)
echo "Sorry, there are no matching result for <b>$search</b>.</br></br>1.
Try more general words. for example: If you want to search 'how to create a website'
then use general keyword like 'create' 'website'</br>2. Try different words with similar
meaning</br>3. Please check your spelling";
else
{
echo "$foundnum results found !<p>";
$per_page = 10;
$start = isset($_GET['start']) ? $_GET['start']: 0;
//echo $start;
$max_pages = ceil($foundnum / $per_page);
if(!$start)
$start=0;
$getquery = pg_query(db_connect(), "SELECT * FROM listings ORDER BY listings.listing_id DESC LIMIT 10 OFFSET $start");
echo "SELECT * FROM listings ORDER BY listings.listing_id DESC LIMIT 10 OFFSET $start <br>";
$i = 1;
echo "\n<table>";
echo "\n<tr><th>TEST</th></tr>";
while($runrows = pg_fetch_assoc($getquery))
{
$listing_id = $runrows['listing_id'];
$user_id = $runrows['user_id'];
$title = $runrows['city'];
$headline = $runrows['headline'];
$description = $runrows['description'];
$bed = $runrows['bedrooms'];
$bath = $runrows['bathrooms'];
echo "\n<tr><td>";
echo $i;
echo "<br/>LISTING ID: $listing_id
<br/>USER: $user_id
<br/>HEADLINE:$headline
<br/>DESCRIPTION: $description
<br/>LOCATION: ".get_property('cities',$title)." # $title</b>
<br/>Bedroom: ". get_property('bedrooms',$bed).
"<br/>Bathroom: ". get_property('washrooms',$bath).
"";
$i +=1;
echo "\n</td></tr>";
}
echo "\n</table>";
//print_r(array_values($runrows));
//Pagination Starts
echo "<center>";
$prev = $start - $per_page;
$next = $start + $per_page;
$adjacents = 3;
$last = $max_pages - 1;
if($max_pages > 1)
{
//previous button
if (!($start<=0))
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$prev'>Prev</a> ";
//pages
if ($max_pages < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
elseif($max_pages > 5 + ($adjacents * 2)) //enough pages to hide some
{
//close to beginning; only hide later pages
if(($start/$per_page) < 1 + ($adjacents * 2))
{
$i = 0;
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($i == $start){
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//in middle; hide some front and some back
elseif($max_pages - ($adjacents * 2) > ($start / $per_page) && ($start / $per_page) > ($adjacents * 2))
{
echo " <a href='search.php?search=$search&submit=Search+source+code&start=0'>1</a> ";
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start/$per_page)+1; $counter < ($start / $per_page) + $adjacents + 2; $counter++)
{
if ($i == $start){
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//close to end; only hide early pages
else
{
echo " <a href='search.php?search=$search&submit=Search+source+code&start=0'>1</a> ";
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start / $per_page) + 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
}
//next button
if (!($start >=$foundnum-$per_page))
echo " <a href='search.php?search=$search&submit=Search+source+code&start=$next'>Next</a> ";
}
echo "</center>";
}
}
?><file_sep><?php
/*
Group 13
September 29, 2016
WEBD3201
The main page
*/
$title = "Home Page";
$date = "September 29, 2016";
$filename = "index.php";
$description = "Home Page for realtor";
include("header.php");
?>
<!--Content body -->
<section class="home" id="home">
<div class="max-width">
<div class="home-content">
<div class="text-1">Only at Durham Region </div>
<div class="text-2">Real Estate Market</div>
<div class="text-3">We have <span class="typing"></span></div>
<a href="listing-cities.php">Search</a>
<?php
//Removes when logged in
if (!isset($_SESSION['loggedin']))
{
echo "<a href=\"login.php\">Login</a>";
}
?>
</div>
</div>
</section>
<!-- about section start -->
<section class="about" id="about">
<div class="max-width">
<h2 class="title">We are top reviewed company</h2>
<div class="about-content">
<div class="column left">
<img src="images/LogoFinal2.png" alt="">
</div>
<div class="column right">
<div class="text">We are here to assist <span class="typing-2"></span></div>
<p>We have helped over thousands of buyers and sellers completing a transaction. We have done this for plenty of years and we will coninue to improve our website for Durham Region.</p>
</div>
</div>
</div>
</section>
<!-- services section start -->
<section class="services" id="services">
<div class="max-width">
<h2 class="title">Our services</h2>
<div class="serv-content">
<div class="card">
<div class="box">
<i class="fas fa-comments-dollar"></i>
<div class="text">Negotiate</div>
<p>Chat with the Seller or Agent to negotiate a price for you.</p>
</div>
</div>
<div class="card">
<div class="box">
<i class="fas fa-search"></i>
<div class="text">Find the new home</div>
<p>Use our advanced search, to discover the new home you may want.</p>
</div>
</div>
<div class="card">
<div class="box">
<i class="fas fa-dollar-sign"></i>
<div class="text">Purchase your home</div>
<p>Purchase the home online, bet for the home you desire. </p>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- showCase section start -->
<section class="showCase" id="showCase">
<div class="max-width">
<h2 class="title">The Current Listings</h2>
<div class="showCase-content">
<div class="column left">
<div class="text">Abundant Number of Houses.</div>
<p>We have a whole list of different houses that have been sold, ready to be sold or is currently being sold.</p>
<a href="#">Read more</a>
</div>
<div class="column right">
<div class="bars">
<div class="info">
<span>Townhouses</span>
<span>18%</span>
</div>
<div class="line html"></div>
</div>
<div class="bars">
<div class="info">
<span>Semi</span>
<span>22%</span>
</div>
<div class="line css"></div>
</div>
<div class="bars">
<div class="info">
<span>Detach</span>
<span>34%</span>
</div>
<div class="line js"></div>
</div>
<div class="bars">
<div class="info">
<span>Apartment</span>
<span>26%</span>
</div>
<div class="line php"></div>
</div>
</div>
</div>
</div>
</section>
<!-- teams section start -->
<section class="teams" id="teams">
<div class="max-width">
<h2 class="title">Our team</h2>
<div class="carousel owl-carousel">
<div class="card">
<div class="box">
<img src="images/profile-1.jpeg" alt="">
<div class="text"><NAME></div>
</div>
</div>
<div class="card">
<div class="box">
<img src="images/profile-2.jpeg" alt="">
<div class="text"><NAME></div>
</div>
</div>
<div class="card">
<div class="box">
<img src="images/profile-3.jpeg" alt="">
<div class="text"><NAME></div>
</div>
</div>
<div class="card">
<div class="box">
<img src="images/profile-4.jpeg" alt="">
<div class="text"><NAME></div>
</div>
</div>
<div class="card">
<div class="box">
<img src="images/profile-5.jpeg" alt="">
<div class="text">Maya Summer</div>
</div>
</div>
</div>
</div>
</section>
<?php include 'footer.php'; ?>
<file_sep>DROP TABLE IF EXISTS salutation;
CREATE TABLE salutation(
value VARCHAR(10)
);
INSERT INTO salutation VALUES ('Mr.');
INSERT INTO salutation VALUES ('Mrs.');
<file_sep><?php
/*
Group 13
November 10, 2016
WEBD3201
User Password Change Page
*/
$title = "Change Password";
$date = "November 2, 2016";
$filename = "user-password.php";
$description = " A page that allows the logined in user to change their current password";
include("header.php");
?>
<?php
$output = "";
$error = "";
$curpassword = "";
$newpassword = "";
$confpassword = "";
// Set id to the username from the session
$id = (isset($_SESSION['username']) )? $_SESSION['username']: "";
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true)
{
if($_SERVER["REQUEST_METHOD"] == "GET")
{
// Defaults when the page loads
$curpassword = "";
$newpassword = "";
$confpassword = "";
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Deafults for the values when the user has submitted new password
$curpassword = trim($_POST["curpassword"]); // The user's current password
$newpassword = trim($_POST["newpassword"]); // The new password the user has entered
$confpassword = trim($_POST["confpassword"]); // Conmfirmation of the new password
$error = "";
// ##Current Password##
// Checks if the user has entered anything for their current password, and if so if it's between the MAX and MIX PASSWORD_LENGTH
if(trim(strlen($curpassword)) == 0 || $curpassword == "")
{
// Generates an error when the user hasn't entered their password
$error .= "Must enter the account's current password <br/>";
$curpassword = "";
$newpassword = "";
$confpassword = "";
}
// Checks if the user has entered the correct password for the account
else if(!($curpassword == $_SESSION['password']) )
{
// Generates an error when the user hasn't entered the right password
$error .= "You must enter the correct current password <br/>";
$curpassword = "";
$newpassword = "";
$confpassword = "";
}
// ##New Password##
// Checks if the user has entered anything for the new password, and if so if it's between the MAX and MIX PASSWORD_LENGTH
if(trim(strlen($newpassword)) == 0 || $newpassword == "")
{
// Generates an error when the user hasn't entered their password
$error .= "Must enter a new password. <br/>";
$curpassword = "";
$newpassword = "";
$confpassword = "";
}
// Checks if the new password is between the min and max lengths
else if(trim(strlen($newpassword)) < MINIMUM_PASSWORD_LENGTH || strlen($newpassword) > MAXIMUM_PASSWORD_LENGTH)
{
// Generates an error if the user's current password is in between the MAX and MIN lengths
$error .= "Your new password must be between ".MINIMUM_PASSWORD_LENGTH." and ".MAXIMUM_PASSWORD_LENGTH." <br/>";
$curpassword = "";
$newpassword = "";
$confpassword = "";
}
// ##Confirm New Password##
// Checks if the new password matches the confirm password
else if(($newpassword) != ($confpassword))
{
// Generates an error when the new & confirm password doesn't match
$error .= "Your new password didn't match the confirm password. <br/>";
$curpassword = "";
$newpassword = "";
$confpassword = "";
}
// ##Database Check/Update##
// Current, new, and confirm passwords are valid from above, connect to the database and check/update
// Checks if the session is avaliable
if($error == "")
{
// Hashes the current password
$hashedCurPass = hash("md5", $curpassword);
// Hashes the new password
$hashedNewPass = hash("md5", $newpassword);
// Execute the prepared statement
pg_execute(db_connect(),"update_user_pass",array($hashedNewPass,$id,$hashedCurPass,));
$_SESSION['password'] = <PASSWORD>;
//------------------------------------------------------------------------------------------------------------------------------------AGENT
if ($_SESSION['user_type'] == GET_AGENT)
{
header("refresh:5;url=dashboard.php");
$output = "<br/>Successful changed your password, you will be redirected to the Dashboard page";
ob_flush();
}
//------------------------------------------------------------------------------------------------------------------------------------USER
else if($_SESSION['user_type'] == GET_USER)
{
header("refresh:5;url=welcome.php");
$output = "<br/>Successful changed your password, you will be redirected to the welcome page";
ob_flush();
}
//------------------------------------------------------------------------------------------------------------------------------------ADMIN
else if($_SESSION['user_type'] == GET_ADMIN)
{
header("refresh:5;url=admin.php");
$output = "<br/>Successful changed your password, you will be redirected to the admin page";
ob_flush();
}
}
}
}
else
{
// If the session is not avaliable, display an error
$error .= "You must be logged in to change password. <br/>";
$error .= "You will be redirected to login page <br/>";
header("Location: login.php");
}
?>
<section class="content-body" id='formSetup'>
<div class="max-width body-place">
<h2 class="title">Password Change</h2>
<p>If you would like to change your current password, then contiune below.
</p>
<h2 style="text-align: center;">Enter your current password and a new password.</h2>
<h3 style="text-align: center;"><?php echo $error; ?> </h3>
<h3 style="text-align: center;"><?php echo $output; ?> </h3>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<br/>
<div class="input-field">
<input type="text" name="username" value="<?php echo $id;?>" size="30" disabled />
<label>Username</label>
</div>
<div class="input-field">
<input type="password" name="curpassword" value="" size="30"/>
<label>Current Password:</label>
</div>
<div class="input-field">
<input type="password" name="newpassword" value="" size="30"/>
<label>New Password:</label>
</div>
<div class="input-field">
<input type="password" name="confpassword" value="" size="30"/>
<label>Confirm Password:</label>
</div>
<input type="submit" value="Submit"/>
</form>
</div>
</section>
<?php include 'footer.php'; ?><file_sep>
UPDATE users SET user_type = 'A' WHERE user_id = 'realtor';
UPDATE users SET user_type = 'D' WHERE user_id = 'abc';
UPDATE users SET user_type = 'U' WHERE user_id = 'Mandy'<file_sep><?php
/*
Group 13
September 29, 2016
WEBD3201
The listing display page
*/
$title = "Listing Display";
$date = "September 29, 2016";
$filename = "index.php";
$description = "The listing display page for individual houses ";
include("header.php");
?>
<?php
if (isset($_GET['listing_id']))
{
$_SESSION['listing_id'] = $_GET['listing_id'];
}
else
{
$_SESSION['listing_id'] = 0;
echo "ERROR: listing information was not find";
}
//$_SESSION['listing_id'] = 3800;
$sql = 'SELECT * FROM listings WHERE listing_id = ' . $_SESSION['listing_id'];
echo "<BR>".$sql;
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
/*
echo "<BR>".pg_fetch_result($result, 0, "listing_id");
echo "<BR>".pg_fetch_result($result, 0, "user_id");
echo "<BR>".pg_fetch_result($result, 0, "status");
echo "<BR>".pg_fetch_result($result, 0, "price");
echo "<BR>".pg_fetch_result($result, 0, "headline");
echo "<BR>".pg_fetch_result($result, 0, "description");
echo "<BR>".pg_fetch_result($result, 0, "postal_code");
echo "<BR>".pg_fetch_result($result, 0, "images");
echo "<BR>".pg_fetch_result($result, 0, "city");
echo "<BR>".pg_fetch_result($result, 0, "property_options");
echo "<BR>".pg_fetch_result($result, 0, "bedrooms");
echo "<BR>".pg_fetch_result($result, 0, "bathrooms");
echo "<BR>".pg_fetch_result($result, 0, "garage");
echo "<BR>".pg_fetch_result($result, 0, "purchase_type");
echo "<BR>".pg_fetch_result($result, 0, "property_type");
echo "<BR>".pg_fetch_result($result, 0, "finished_basement");
echo "<BR>".pg_fetch_result($result, 0, "open_house");
echo "<BR>".pg_fetch_result($result, 0, "schools");*/
?>
<h1> Listing Display </h1>
<hr/>
<table style="width:50%" border="1px solid black">
<tr>
<th>Listing Image</th>
<th>Listing Description</th>
</tr>
<tr>
<th rowspan="2">
<img src="Houses/brampton_house.jpg" alt="Oshawa House" width="300px" height="200px"/>
</th>
<td align="left" valign="top">
<h3><?php echo pg_fetch_result($result, 0, "headline") ?></h3>
<ul>
<li>Open house?: <?php echo get_property('open_house', pg_fetch_result($result, 0, "open_house"))?> </li>
<li>Finished Basement?: <?php echo get_property('finished_basement', pg_fetch_result($result, 0, "finished_basement"))?></li>
<li><?php echo get_property('purchase_type', pg_fetch_result($result, 0, "purchase_type"))?></li>
<li>Garage Type: <?php echo get_property('garage_type', pg_fetch_result($result, 0, "garage"))?></li>
<li>Near school?: <?php echo get_property('schools', pg_fetch_result($result, 0, "schools"))?></li>
<li>Status: <?php echo get_property('listing_status', strtolower(pg_fetch_result($result, 0, "status"))) ?></li>
<li>Washrooms: <?php echo get_property('washrooms',pg_fetch_result($result, 0, "bathrooms")) ?></li>
<li>Bedrooms: <?php echo get_property('bedrooms',pg_fetch_result($result, 0, "bedrooms")) ?></li>
<li>Description: <?php echo pg_fetch_result($result, 0, "description") ?></li>
</ul>
</td>
</tr>
<tr>
<td align="left" valign="top"><ul>
<li>Location: <?php echo get_property('cities',pg_fetch_result($result, 0, "city")) ?></li>
<li>Postal Code: <?php echo pg_fetch_result($result, 0, "postal_code") ?></li>
<li>Price: <?php echo pg_fetch_result($result, 0, "price") ?></li>
</ul>
</td>
</tr>
</table>
<form action="listing-matches.php">
<p>
<input type="submit" name="submit" value="Back"/></p>
</form>
<?php include 'footer.php'; ?><file_sep>SELECT * FROM LISTINGS<file_sep><?php
/*
Group 13
December 1, 2016
WEBD3201
The Acceptable Use Policy page
*/
$title = "Acceptable Use Policy";
$date = "December 1, 2016";
$filename = "aup.php";
$description = "'Acceptable Use policy for users to read";
include("header.php");
?>
<section class="content-body policy" id='result'>
<div class="max-width body-place">
<h2 class="title">Acceptable Use Policy</h2>
<h2>Overview</h2>
<p>The purpose of this policy is to establish acceptable and unnacceptable use of <?php echo WEBSITE_NAME; ?> in conjuction with its established trust and behaviour.</p>
<p><?php echo WEBSITE_NAME; ?> provides informational systems to manage listings to be viewed to users that are interested and must be managed responsibly to maintain confidentiality and verified to users. This policy requires the users on <?php echo WEBSITE_NAME; ?> to conform to the appropriate uses of this site to protect against legal issues.<br/>
</p>
<h2> Scope </h2>
<p>
All clients, agents, admins, and any other personnel affiliated with <?php echo WEBSITE_NAME; ?> must adhere to this policy. <br/>
</p>
<h2> Policy Statement </h2>
<p>
You are responsible for exercising a conventional use <?php echo WEBSITE_NAME; ?> resources in accordance with <?php echo WEBSITE_NAME; ?> policies, standards, and guidelines. <?php echo WEBSITE_NAME; ?> resources and other provided information may not be used for any unlawful or prohibited purposes.
<br/>
</p>
<p>
Users of <?php echo WEBSITE_NAME; ?> that interfere with other users on <?php echo WEBSITE_NAME; ?> may be disconnected from <?php echo WEBSITE_NAME; ?>.
</p>
<br/>
<h2> System Accounts </h2>
<p>
You are responsible for the security of data, accounts, and systems under your control. Keep passwords secure and do not share account or password information with anyone including other personnel or friends. You must maintain system-level and user-level passwords in accordance with the Password Policy.
</p>
<p>
You must ensure through legal or technical means that proprietary information remains within the control of <?php echo WEBSITE_NAME; ?> at all times.
</p>
<h2> Computing Assets </h2>
<p>
All PCs, PDAs, laptops, and workstations must be secured with a password-protected screensaver with the automatic activation feature set to 10 minutes or less. You must lock the screen or log off when the device is unattended.
</p>
<h2> Network Use </h2>
<p> You are responsible for the security and appropriate use of <?php echo WEBSITE_NAME; ?> network resources under your control. Using <?php echo WEBSITE_NAME; ?> resources for the following is strictly prohibited:
</p>
<ul>
<li>Causing a security breach to either <?php echo WEBSITE_NAME; ?> or other network resources, including, but not limited to, accessing data, servers, or accounts to which you are not authorized; circumventing user authentication on any device; or sniffing network traffic.</li>
<li>Causing a disruption of service to either <?php echo WEBSITE_NAME; ?> or other network resources, including, but not limited to, ICMP floods, packet spoofing, denial of service, heap or buffer overflows, and forged routing information for malicious purposes.</li>
<li>Violating copyright law, including, but not limited to, illegally duplicating or transmitting copyrighted pictures.</li>
<li>Intentionally introducing malicious code, including, but not limited to, viruses, worms, Trojan horses, e-mail bombs, spyware, adware, and keyloggers.</li>
</ul>
<h2> Electronic Communications </h2>
<p>
The following are strictly prohibited:
</p>
<ul>
<li>Sending Spam via e-mail, text messages, pages, instant messages, voice mail, or other forms of electronic communication.</li>
<li>Forging, misrepresenting, obscuring, suppressing, or replacing a user identity on any electronic communication to mislead the recipient about the sender.</li>
<li>Posting duplicates of a listing to <?php echo WEBSITE_NAME; ?>.</li>
</ul>
<h2> Enforcement </h2>
<p>
An agent, client, or admin found to have violated this policy may be subject to disciplinary action up to and including termination of the account.
</p>
<br/>
<h2>Definitions</h2>
<table>
<tr>
<th>Term</th>
<th>Defnition</th>
</tr>
<tr>
<td>Spam</td>
<td>Electronic junk mail or junk newsgroup postings. Messages that are unsolicited, unwanted, and irrelevant.</td>
</tr>
</table>
<br/>
<h2>Revision History</h2>
<table>
<tr>
<th>Date Of Change</th>
<th>Responsible</th>
<th>Summary of Change</th>
</tr>
<tr>
<td>2016-12-01</td>
<td><?php echo WEBSITE_NAME; ?></td>
<td>Policy Created</td>
</tr>
</table>
<br/>
</div>
</section>
<?php include 'footer.php'; ?>
<file_sep> <!-- footer section start -->
<footer>
<span>[<a href="privacy_policy.php">Privacy Policy</a>] [<a href="aup.php">Acceptance Use Policy</a>] | <span class="far fa-copyright"></span> <?php displayCopyright(); ?> All rights reserved.</span>
</footer>
<script src="js/script.js"></script>
<script src="js/next.js"></script>
</body>
</html><file_sep>--Group 13
--cities.sql
--October 19, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS cities;
--Creates the table again
CREATE TABLE cities(
value SMALLINT PRIMARY KEY,
property VARCHAR(30) NOT NULL
);
--Inserts rows inside the table
INSERT INTO cities (value, property) VALUES (1, 'Ajax');
INSERT INTO cities (value, property) VALUES (2, 'Brooklin');
INSERT INTO cities (value, property) VALUES (4, 'Bowmanville');
INSERT INTO cities (value, property) VALUES (8, 'Oshawa');
INSERT INTO cities (value, property) VALUES (16, 'Pickering');
INSERT INTO cities (value, property) VALUES (32, 'Port Perry');
INSERT INTO cities (value, property) VALUES (64, 'Whitby');<file_sep><?php
/*
Group 13
November 10, 2016
WEBD3201
The list preview page that will show single houses.
*/
$title = "Display Preview";
$date = "November 06, 2016";
$filename = "listing-matches.php";
$description = "The listing display page for individual house listing ";
include("header.php");
?>
<?php
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$favouriteFound = 0;
$reportFound = 0;
$_SESSION['listing_id'] = (isset($_GET['listing_id']))? $_GET['listing_id']: 0;
if (isset($_GET['listing_id']))
{
//$_SESSION['listing_id'] = $_GET['listing_id'];
}
else
{
//$_SESSION['listing_id'] = 0;
echo "ERROR: listing information was not find but please look at our first ever house on our website for 30 seconds";
header("refresh:30;url=listing-cities.php");
ob_flush();
}
$sql = 'SELECT * FROM listings WHERE listing_id = ' . $_SESSION['listing_id'];
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
$owner = pg_execute(db_connect(),"user_check",array(pg_fetch_result($result, 0, "user_id")));
$owner2 = pg_execute(db_connect(),"Get_Personal",array(pg_fetch_result($result, 0, "user_id")));
//Admin can check all pages
if (isset($_SESSION['user_type']) && $_SESSION['user_type'] == GET_ADMIN)
{
}
//Checks if the creator tries to enter a disabled webpage
else if (pg_fetch_result($result, 0, "status") == DISABLED)
{
header("Location: listing-cities.php");
}
//Checks if the creator tries to enter a disabled webpage
else if (pg_fetch_result($result, 0, "status") == CLOSED)
{
header("Location: listing-cities.php");
}
if (isset($_POST['submit']))
{
header("location: ".$_SESSION['previousPage']);
}
if (isset($_POST['disable']))
{
echo "Disable";
$disable = "UPDATE listings SET status='".DISABLED."' WHERE listing_id=". $_SESSION['listing_id'];
pg_query(db_connect(), $disable);
$disable_user = "UPDATE users SET user_type='".GET_DISABLED."' WHERE user_id='". pg_fetch_result($result, 0, "user_id")."';";
pg_query(db_connect(), $disable_user);
//Closes any existing reports related to the page
$getReports = pg_query(db_connect(), "SELECT * FROM reports JOIN users ON reports.user_id = users.user_id JOIN people ON users.user_id = people.user_id WHERE listing_id=".$_SESSION['listing_id']);
while($runrows = pg_fetch_assoc($getReports))
{
$user_id = $runrows['user_id'];
$listing_id = $runrows['listing_id'];
$date = $runrows['reported_on'];
$firstNameReport = $runrows['first_name'];
$lastNameReport = $runrows['last_name'];
$close = "UPDATE reports SET status='".CLOSED."' WHERE listing_id=". $_SESSION['listing_id'];
pg_query(db_connect(), $close);
}
header("Location: $actual_link");
}
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['user_type'] == GET_USER)
{
//--------------------------------------------------------------------------------------------------------FAVOURITES
if (isset($_POST['favourite']))
{
$insertSQL = "INSERT INTO favourites VALUES('".$_SESSION['username']."', '".$_SESSION['listing_id']."')";
pg_query(db_connect(), $insertSQL);
}
//------------------------------------------------Unfavourite
if (isset($_POST['unfavourite']))
{
$insertSQL = "DELETE FROM favourites WHERE user_id ='".$_SESSION['username']."' AND listing_id ='".$_SESSION['listing_id']."';";
pg_query(db_connect(), $insertSQL);
}
$favouriteSQL = "SELECT * FROM favourites WHERE user_id = '".$_SESSION['username']."' AND listing_id = '".$_SESSION['listing_id']."'";
$fav = pg_query(db_connect(), $favouriteSQL);
$favRow = pg_num_rows($fav);
if ($favRow == 1)
{
$favouriteFound = 1;
}
else
{
$favouriteFound = 0;
}
//-------------------------------------------------------------------------------------------END FAVOURITES
//______________________________________________REPORT
if (isset($_POST['report']))
{
$insertSQL = "INSERT INTO reports VALUES('".$_SESSION['username']."', '".$_SESSION['listing_id']."', '".date("Y-m-d",time())."', '".OPEN."')";
pg_query(db_connect(), $insertSQL);
$reportFound = 1;
}
$reportSQL = "SELECT * FROM reports WHERE user_id = '".$_SESSION['username']."' AND listing_id = '".$_SESSION['listing_id']."'";
$report = pg_query(db_connect(), $reportSQL);
$reportRow = pg_num_rows($report);
if ($reportRow == 1)
{
$reportFound = 1;
}
else
{
$reportFound = 0;
}
}
//Folder location
$dirname = "./listing/".pg_fetch_result($result, 0, "listing_id")."/";
//Gets any images in folder
$images = glob($dirname."*");
?>
<!-- about section start -->
<section class="content-body result" id='result'>
<div class="max-width body-place">
<h2 class="title"><?php echo pg_fetch_result($result, 0, "headline") ?></h2>
<div class="row-info">
<div class="column left">
<?php
if (file_exists("./listing/".pg_fetch_result($result, 0, "listing_id")."/".pg_fetch_result($result, 0, "listing_id")."_".pg_fetch_result($result, 0, "images").".jpg"))
{
echo "<img src=\"./listing/".pg_fetch_result($result, 0, "listing_id")."/".pg_fetch_result($result, 0, "listing_id")."_".pg_fetch_result($result, 0, "images").".jpg\" alt=\"House Image\" width=\"300px\"/>";
}
else
{
echo "<img src=\"images/notFound.jpg\" alt=\"Image Not Found\" width=\"300px\" />";
}
$i = 1;
echo "<br/>";
array_shift($images);//Removes the first array element
//Shows the rest of the images about the house
foreach($images as $image) {
//Searchs for the underscore
$testeee = strrpos($image, '_', 0) +1;
//Gets the number infront
$rest = substr($image, $testeee, 1);
echo '<img src="'.$image.'" width="50px" /> ';
$i +=1;
}
?>
</div>
<div class="column right">
<ul>
<li>Open house?: <?php echo get_property('open_house', pg_fetch_result($result, 0, "open_house"))?> </li>
<li>Finished Basement?: <?php echo get_property('finished_basement', pg_fetch_result($result, 0, "finished_basement"))?></li>
<li><?php echo get_property('purchase_type', pg_fetch_result($result, 0, "purchase_type"))?></li>
<li>Garage Type: <?php echo get_property('garage_type', pg_fetch_result($result, 0, "garage"))?></li>
<li>Near school?: <?php echo get_property('schools', pg_fetch_result($result, 0, "schools"))?></li>
<li>Status: <?php echo get_property('listing_status', strtolower(pg_fetch_result($result, 0, "status"))) ?></li>
<li>Washrooms: <?php echo get_property('washrooms',pg_fetch_result($result, 0, "bathrooms")) ?></li>
<li>Bedrooms: <?php echo get_property('bedrooms',pg_fetch_result($result, 0, "bedrooms")) ?></li>
<li>Description: <?php echo pg_fetch_result($result, 0, "description") ?></li>
</ul>
<ul>
<li>Location: <?php echo get_property('cities',pg_fetch_result($result, 0, "city")) ?></li>
<li>Postal Code: <?php echo pg_fetch_result($result, 0, "postal_code") ?></li>
<li>Price: $<?php echo number_format(pg_fetch_result($result, 0, "price") , 2)?></li>
</ul>
</div>
</div>
<div class="row-info">
<div class="column right">
<h2>Seller: </h2>
<p>Name: <?php echo pg_fetch_result($owner2, 0, "first_name")?> <?php echo pg_fetch_result($owner2, 0, "last_name")?> </p>
<p>Email: <?php echo pg_fetch_result($owner, 0, "email_address")?></p>
<p>Main phone number: <?php echo pg_fetch_result($owner2, 0, "primary_phone_number")?></p>
<p>Second phone number: <?php echo pg_fetch_result($owner2, 0, "secondary_phone_number")?></p>
</div>
</div>
<div class="row-info">
<form action="<?php echo $actual_link; ?>" method="post">
<?php
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['user_type'] == GET_ADMIN)
{
//If list is already disabled, then no button
if (pg_fetch_result($result, 0, "status") == DISABLED)
{
echo "<input style=\"align: center\" type=\"submit\" name=\"disable\" value=\"Disabled Already\" disabled/>";
}
else
{
echo "<input style=\"align: center\" type=\"submit\" name=\"disable\" value=\"Disable\" />";
}
}
else if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['user_type'] == GET_USER)
{
//Checks if page has been favourited by user or not
if ($favouriteFound == 1)
{
echo "<input style=\"align: center\" type=\"submit\" name=\"unfavourite\" value=\"Unfavourite\" />";
}
else
{
echo "<input style=\"align: center\" type=\"submit\" name=\"favourite\" value=\"Favourite\" />";
}
//Checks if page has been reported by user already
if ($reportFound == 1)
{
echo "<input style=\"align: center\" type=\"submit\" name=\"REPORTED\" value=\"Reported Already\" disabled/>";
}
else
{
echo "<input style=\"align: center\" type=\"submit\" name=\"report\" value=\"Report\" />";
}
}
?>
</form>
</div>
<div class="row-info btn-back">
<form action="listing-view.php" method="post">
<input style="align: center" type="submit" name="submit" value="Back" />
</form>
</div>
</div>
</section>
<?php include 'footer.php'; ?><file_sep><?php
/*
Group 13
September 29, 2016
WEBD3201
The Welcome Page
*/
$title = "Welcome";
$date = "September 29, 2016";
$filename = "index.php";
$description = " A page that welcomes the agent";
include("header.php");
?>
<?php
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['user_type'] == GET_USER)
{
echo "<section class=\"content-body result\" id='result'>
<div class=\"max-width body-place\">
<h2 class=\"title\">Welcome to the User's area, " . $_SESSION['username'] . "!</h2>
<div class=\"row-info\">";
echo "\n<br/>Password: ".$_SESSION['password']." User Type: ".$_SESSION['user_type']."";
echo "\n<br/>Email: " .$_SESSION['email']. " Enrolled Date: ". $_SESSION['enrol']."";
echo "\n<br/> Last Access: ".$_SESSION['last_access']."";
echo "\n<br/> Personal Information";
echo "\n<br/> Salutation: ".$_SESSION['salutation']."";
echo "\n<br/> First Name: ".$_SESSION['first_name']."";
echo "\n<br/> Last Name: ".$_SESSION['last_name']."";
echo "\n<br/> 1st Street: ".$_SESSION['street_address_1']."";
echo "\n<br/> 2nd Street: ".$_SESSION['street_address_2']."";
echo "\n<br/> City: ".$_SESSION['city']."";
echo "\n<br/> Provinces: ".$_SESSION['province']."";
echo "\n<br/> Primary Phone: ". $_SESSION['primary_phone']."";
echo "\n<br/> Secondary Phone: ". $_SESSION['secondary_phone']."";
echo "\n<br/> Fax Number: ". $_SESSION['fax']."";
echo "\n<br/> Preferred Contact Method: ".$_SESSION['contact_method']."";
if (isset($_GET['listing_id']) )
{
$insertSQL = "DELETE FROM favourites WHERE user_id ='".$_SESSION['username']."' AND listing_id ='".$_GET['listing_id']."';";
pg_query(db_connect(), $insertSQL);
header("Location: welcome.php");
}
//SQL code
$sql = "SELECT * FROM favourites JOIN listings ON favourites.listing_id = listings.listing_id WHERE favourites.user_id='".$_SESSION['username']."'";
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
echo "<br/><br/>";
$search = $sql;
if (isset($_GET ['submit']))
{
$button = $_GET ['submit'];
$search = $sql;
}
$search_exploded = explode (" ", $search);
$x = "";
$construct = $sql;
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="title LIKE '%$search_each%'";
else
$construct .="AND title LIKE '%$search_each%'";
}
//USED TO MAKE THE NUMBER OF PAGINATE
$constructs = $sql;
//echo $constructs;
$run = pg_query(db_connect(),$constructs);
$foundnum = pg_num_rows($run);
//Shows the number of results match the criteria
echo "<h2 align=\"center\">Show Favourites </h2>";
//echo "<p>$foundnum results found !<p>";
//sets the number of houses per pages
$per_page = PAGE_LIMIT;
$start = isset($_GET['start']) ? $_GET['start']: 0;
//find the appropriate number of pages needed to display the page
$max_pages = ceil($foundnum / $per_page);
//Page starts at the first records
if(!$start)
$start=0;
//Set up the query
$getquery = pg_query(db_connect(), $sql. " LIMIT $per_page OFFSET $start");
//echo $_SESSION['Where']. " ORDER BY listings.listing_id DESC LIMIT $per_page OFFSET $start <br>";
//_______________________________________________________________________________________________________CREATES THE TABLE
echo "\n<table border=\"0\">";
$i=0;
while($runrows = pg_fetch_assoc($getquery))
{
$listing_id = $runrows['listing_id'];
$user_id = $runrows['user_id'];
$city = $runrows['city'];
$headline = $runrows['headline'];
$description = $runrows['description'];
$bed = $runrows['bedrooms'];
$bath = $runrows['bathrooms'];
$price = $runrows['price'];
$property = $runrows['property_type'];
$garage = $runrows['garage'];
$schools = $runrows['schools'];
$image = $runrows['images'];
$status = $runrows['status'];
if ($i == 0)
{
echo "<tr><th>Image</th><th>Headline</th><th>Unfavourite</th></tr>";
}
$i +=1;
echo "\n<tr><td> ";
if (file_exists("./listing/$listing_id/".$listing_id."_".$image.".jpg"))
{
echo "<img src=\"./listing/$listing_id/".$listing_id."_".$image.".jpg\" alt=\"House Image\" width=\"200px\"/>";
}
else
{
echo "<img src=\"images/notFound.jpg\" alt=\"Image Not Found\" width=\"200px\" />";
}
echo "\n</td>";
echo "\n<td >";
if ($status == OPEN)
{
echo "<br/><b><a class=\"homelist\" href=\"listing-view.php?submit=Search+source+code&listing_id=$listing_id\" >$headline </a></b> ";
}
else if ($status == DISABLED)
{
echo "<br/><b><a class=\"homelist\" >$headline (Not Available) </a></b> ";
}
else
{
echo "<br/><b><a class=\"homelist\" >$headline (SOLD) </a></b> ";
}
echo "\n</td> \n\t\t<td> <a class=\"homelist\" href=\"welcome.php?listing_id=$listing_id\" >Remove From Favourites </a> </td> </tr>";
echo "\n<tr><td colspan=\"3\">";
echo "\n\t<hr/>";
echo "\n</td></tr>";
}
echo "\n</table>";
//Pagination Starts
echo "<center>";
$prev = $start - $per_page;
$next = $start + $per_page;
$adjacents = 3;
$last = $max_pages - 1;
if($max_pages > 1)
{
//previous button
if (!($start<=0))
echo " <a href='welcome.php?submit=Search+source+code&start=$prev'>Prev</a> ";
//In the first 6 pages, it doesn't skip
if ($max_pages < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='welcome.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='welcome.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
elseif($max_pages > 5 + ($adjacents * 2)) //enough pages to hide some but the first two and the next 3 pages
{
//close to beginning; only hide later pages
if(($start/$per_page) < 1 + ($adjacents * 2))
{
$i = 0;
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($i == $start){
echo " <a href='welcome.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='welcome.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//in middle; hide some front and some back
elseif($max_pages - ($adjacents * 2) > ($start / $per_page) && ($start / $per_page) > ($adjacents * 2))
{
echo " <a href='welcome.php?submit=Search+source+code&start=0'>1</a> ";
echo " <a href='welcome.php?submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start/$per_page)+1; $counter < ($start / $per_page) + $adjacents + 2; $counter++)
{
if ($i == $start){
echo " <a href='welcome.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='welcome.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//close to end; only hide early pages
else
{
echo " <a href='welcome.php?submit=Search+source+code&start=0'>1</a> ";
echo " <a href='welcome.php?submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start / $per_page) + 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='welcome.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='welcome.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
}
//next button
if (!($start >=$foundnum-$per_page))
echo " <a href='welcome.php?submit=Search+source+code&start=$next'>Next</a> ";
}
echo "</center>";
echo "</form>";
echo "</div>
</div>
</section>";
}
else
{
header("Location: /");
}
?>
<?php include 'footer.php'; ?>
<file_sep>--Group 13
--bedrooms.sql
--October 19, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS bedrooms;
--Creates the table again
CREATE TABLE bedrooms(
value INT PRIMARY KEY,
property VARCHAR(30) NOT NULL
);
--Inserts rows inside the table
INSERT INTO bedrooms (value, property) VALUES (1, '1');
INSERT INTO bedrooms (value, property) VALUES (2, '2');
INSERT INTO bedrooms (value, property) VALUES (4, '3');
INSERT INTO bedrooms (value, property) VALUES (8, '4');
INSERT INTO bedrooms (value, property) VALUES (16, '5 or more');<file_sep>--Group 13
--property_options.sql
--October 19, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS property_options;
--Creates the table again
CREATE TABLE property_options(
value INT PRIMARY KEY,
property VARCHAR(30) NOT NULL
);
--Inserts rows inside the table
INSERT INTO property_options (value, property) VALUES (1, 'AC');
INSERT INTO property_options (value, property) VALUES (2, 'Pool');
INSERT INTO property_options (value, property) VALUES (4, 'Fireplace');<file_sep><?php
/*
Group 13
November 9, 2016
WEBD3201
The listing cities page
*/
$title = "Listing Cities";
$date = "November 9, 2016";
$filename = "listing-cities.php";
$description = "The Listing cities page";
include("header.php");
?>
<?php
$cities_table = 'cities';
$city = (isset($_COOKIE[$cities_table]))?$_COOKIE[$cities_table]:0;
if (isset($_GET['city']))
{
$dumValid = $_GET['city'];
}
if($_SERVER["REQUEST_METHOD"] == "GET")
{
//default mode when the page loads the first time
//can be used to make decisions and initialize variables
//ROW 2
$minimum = "";
$maximum = "";
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
if (isset($_POST[$cities_table]))
{
$city = sumCheckBox($_POST[$cities_table]);
setcookie($cities_table, $city, time()+ COOKIE_LENGTH, "/");
}
else
{
$city = 0;
setcookie($cities_table, $city, time()+ COOKIE_LENGTH, "/");
}
$_SESSION['city'] = $city;
//echo $_SESSION['city'];
header("Location: listing-search.php");
}
?>
<script type="text/javascript">
<!--
/*NOTE: for the following function to work, on your page
you have to create a checkbox id'ed as city_toggle
<input type="checkbox" onclick="toggle(this);" name="city[]" value="0">
and each city checkbox element has to be an named as an
array (specifically named "city[]")
e.g.
<input type="checkbox" name="city[]" value="1">Ajax
*/
function toggle(source) {
checkboxes = document.getElementsByName('cities[]');
for(i = 0; i < checkboxes.length; i++)
{
checkboxes[i].checked = source.checked;
}
}
//-->
</script>
<br/>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<tr>
<td align="left">
<?php
//SELECT ALL OPTIONS
echo "\n<input type=\"checkbox\" onclick=\"toggle(this);\" name=\"".$cities_table."[]\" value=\"0\" /> Select All<br/>";
echo build_checkbox($cities_table, $city);
?>
</td>
<td>
<!-- Image Map Generated by http://www.image-map.net/ -->
<img src="images/imagemap.jpg" alt="DURHAM REGION MAP" usemap="#image-map" />
<map name="image-map" id="image-map" >
<area alt="Pickering" title="Pickering" href="./listing-search.php?submit=Search+source+code&city=16" coords="13,205,188,205,188,297,114,296,107,301,103,309,108,315,112,319,99,347,101,359,104,367,114,377,118,385,114,401,104,406,94,404,79,388,71,381,63,383,54,397,52,401,33,400,24,393,14,382,10,372,8,351,7,330" shape="poly" />
<area alt="Ajax" title="Ajax" href="./listing-search.php?submit=Search+source+code&city=1" coords="112,310,112,306,148,305,188,306,188,402,125,402,125,377,113,363,109,354,109,345,117,336,120,326,121,318,119,312" shape="poly" />
<area alt="Brooklin" title="Brooklin" href="./listing-search.php?submit=Search+source+code&city=2" coords="197,275,286,207" shape="rect" />
<area alt="Oshawa" title="Oshawa" href="./listing-search.php?submit=Search+source+code&city=8" coords="349,402,364,401,371,404,377,404,379,401,380,322,380,206,295,208,295,344,294,383,294,396,294,401,290,403,290,405,300,407,310,404,320,404,333,403" shape="poly" />
<area alt="Whitby" title="Whitby" href="./listing-search.php?submit=Search+source+code&city=64" coords="198,282,286,282,286,394,274,400,264,398,255,394,241,386,228,389,213,394,207,394,198,394,198,342" shape="poly" />
<area alt="Bowmanville" title="Bowmanville" href="./listing-search.php?submit=Search+source+code&city=4" coords="642,237,755,236,755,429,752,442,738,444,706,442,676,439,658,438,640,430,623,425,604,423,586,420,567,416,551,411,533,409,503,418,495,423,476,425,460,422,445,415,429,414,403,411,388,405,388,213,565,213,564,237" shape="poly" />
<area alt="Port Perry" title="Port Perry" href="./listing-search.php?submit=Search+source+code&city=32" coords="388,203,565,203,559,63,425,127,420,124,462,60,467,40,462,34,455,31,439,33,420,39,404,55,392,74,382,99,379,102,377,96,379,30,382,17,380,12,361,12,197,12,195,195,192,199,261,199,388,199" shape="poly" />
</map>
</td>
</tr>
<tr>
<td colspan="2">
<br/>
<input style="align: center" type="submit" name="submit" value="Submit" />
<br/>
</td>
</tr>
</table>
</form>
<?php include 'footer.php'; ?><file_sep>-- File: contact_method.sql
-- Author: GROUP13
-- Date: October 19, 2016
-- Description: SQL file to create listing status property/value table
DROP TABLE IF EXISTS contact_method;
CREATE TABLE contact_method(
value CHAR(1) PRIMARY KEY,
property VARCHAR(30) NOT NULL
);
INSERT INTO contact_method(value, property) VALUES ('E', 'Email');
INSERT INTO contact_method(value, property) VALUES ('P', 'Phone');
INSERT INTO contact_method(value, property) VALUES ('T', 'Text');
<file_sep>UPDATE users SET password = '<PASSWORD>' WHERE user_id = 'aladila';<file_sep>SELECT * FROM users WHERE user_type='D'<file_sep><?php
/*
Group 13
November 10, 2016
WEBD3201
The list preview page that will show single houses.
*/
$title = "***";
$date = "November 06, 2016";
$filename = "listing-matches.php";
$description = "The listing display page for individual house listing ";
include("header.php");
?>
<?php
$list_id = 3728;
$dirname = "listing/$list_id/";
$images = glob($dirname."*");
$sql = "SELECT * FROM listings WHERE listing_id = $list_id";
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
//lists agents listings: SELECT * FROM listings WHERE user_id = 'aladila'
//Must have the user log in
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin']==false)
{
header("Location: login.php");
}
else if ($_SESSION['username'] != pg_fetch_result($result, 0, "user_id") )
{
echo $_SESSION['username']." is not owner. ".pg_fetch_result($result, 0, "user_id")." is the owner";
}
else if ($_SESSION['user_type'] != GET_AGENT)
{
header("Location: index.php");
}
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$target_dir = "./listing/$list_id/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false)
{
echo "<BR>File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "<BR>File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "<BR>Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > IMAGE_SIZE_LIMIT) {
echo "<BR>Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" ) {
echo "<BR>Sorry, only JPG file are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}
else
{
echo "<br>$target_dir".$_FILES["fileToUpload"]["name"];
if (is_dir($target_dir))
{
echo "<BR>Folder exist";
//mkdir("./".$list_id."/", 0777)
}
else
{
echo "<BR>Folder does not exist";
mkdir("$target_dir", 0777);
}
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo "<BR>Permissions: ".chmod("$target_dir".$_FILES["fileToUpload"]["name"], 0777)."";
echo "<BR>code: chmod(\"$target_dir". $_FILES["fileToUpload"]["name"].", 0777).";
//Changes permission
chmod("$target_dir".$_FILES["fileToUpload"]["name"], 0777);
$filecount = 0;
if ($images){
$filecount = count($images);
echo $filecount;
}
$trust = true;
$newName = $target_dir ."".$list_id."_". $filecount.".jpg";
echo $newName;
$i = 0;
do {
echo "<BR>Loop $i";
$newName = $target_dir ."".$list_id."_". $i.".jpg";
if (file_exists($newName) )
{
$i +=1;
}
else
{
rename("$target_dir".$_FILES["fileToUpload"]["name"], $newName);
$trust = false;
}
} while ($trust);
//rename("$target_dir".$_FILES["fileToUpload"]["name"], $newName);
echo "<BR>The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
//header("Location: test3.php");
} else {
echo "<BR>Sorry, there was an error uploading your file.";
}
}
}
if (isset($_POST["save"]))
{
echo "SAVED";
}
?>
<form action="test3.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<form action="test3.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="submit" value="Save Image" name="save">
<input type="submit" value="Delete Chosen Images" name="delete">
<?php
echo "<table border=\"1\">";
echo "<tr>";
echo "<th>Image</th><th>Checkbox</th>";
echo "</tr>";
//Loops any images that has been found
foreach($images as $image) {
echo "\n";
echo "<tr>";
echo "\n\t<td>";
echo '<a href="test3.php?submit=Search+source+code&remove='.$image.'"><img src="'.$image.'" width=\"100\"/></a><br />';
echo "\n\t\t</td>";
echo "\n\t\t<td><input name=\"formDoor[]\" type=\"checkbox\" class=\"select\" value=\"$image\"/></td>";
echo "\n\t</tr>";
}
echo "</table>";
echo "</form>";
if (isset($_GET['remove']))
{
$dumValid = $_GET['remove'];
if (file_exists($dumValid) )
{
if (!unlink($dumValid))
{
echo ("Error deleting $dumValid");
}
else
{
echo ("Deleted $dumValid");
}
$filecount = 0;
if ($images){
$filecount = count($images);
$filecount -= 1;
echo $filecount;
}
//Removes the file if there is no more files in the folder
if ($filecount == 0)
{
rmdir($dirname);
echo "<br>Remove Folder";
}
header("Location: test3.php");
}
else
{
echo "Invalid file name";
}
}
if (isset($_POST["delete"]))
{
echo "Delete Clicked";
if (isset($_POST['formDoor']) )
{
echo "test";
$test23 = $_POST['formDoor'];
print_r($test23);
foreach ($test23 as $file)
{
echo "<br>File selected: ".$file;
if(file_exists($file))
{
unlink($file);
echo "<br>Delete file";
}
$filecount = 0;
if ($images){
$filecount = count($images);
$filecount -= count($test23);
echo "<br>file count: ".$filecount;
}
//Removes the file if there is no more files in the folder
}
if ($filecount <= 0)
{
rmdir($dirname);
echo "<br>Remove Folder";
}
echo "Files deleted successfully.";
}
}
?>
<?php include 'footer.php'; ?>
<file_sep>--Group 13
--users.sql
--September 29, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS users;
--Creates the table again
CREATE TABLE users(
user_id VARCHAR(20) PRIMARY KEY NOT NULL,
password VARCHAR(32) NOT NULL,
user_type CHAR(1) NOT NULL,
email_address VARCHAR(255) NOT NULL,
enrol_date DATE NOT NULL,
last_access DATE NOT NULL
);
--Inserts rows inside the table
INSERT INTO users VALUES('realtor','<PASSWORD>','R','<EMAIL>','2016-1-1','2016-2-1'); -- testpass
INSERT INTO users VALUES('aladila','36341cbb9c5a51ba81e855523de49dfd','R','<EMAIL>','2016-3-13','2016-3-22'); --amar
INSERT INTO users VALUES('abc','202cb962ac59075b964b07152d234b70','R','<EMAIL>','2016-3-22','2016-3-4'); -- 123
INSERT INTO users VALUES('Mandy','1c625cc86f824660a320d185916e3c55','R','<EMAIL>','2016-4-20','2016-3-4'); --russia
<file_sep><!--
Programmer: Group_13
Program Name: <?php echo $filename; ?>
Date: <?php echo $date; ?>
Purpose: <?php echo $description; ?>
-->
<?php session_start();
require("./includes/constants.php");
require("./includes/functions.php");
require("./includes/db.php");
ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="images/LogoFinal_Icon.ico" />
<!-- <link rel="stylesheet" type="text/css" href="css/webd3201.css"/> -->
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.11/typed.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css"/>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> -->
<title><?php echo $title; ?> </title>
</head>
<body>
<div class="scroll-up-btn">
<i class="fas fa-angle-up"></i>
</div>
<nav class="navbar">
<div class="max-width">
<div class="logo"><a href="/">Houses<span>Connected.</span></a></div>
<ul class="menu">
<?php
//Shows only for CLIENTS
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['user_type'] == GET_USER)
{
echo "<li><a href=\"./welcome.php\" class=\"menu-btn\">Welcome</a></li>";
}
//Shows only for AGENTS
else if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['user_type'] == GET_AGENT)
{
echo "<li><a href=\"./dashboard.php\" class=\"menu-btn\">Dashboard</a></li>";
echo "<li><a href=\"./listing-create.php\" class=\"menu-btn\">List Create</a></li>";
}
//Shows only for ADMIN
else if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['user_type'] == GET_ADMIN)
{
echo "<li><a href=\"./admin.php\" class=\"menu-btn\">Admin</a></li>";
echo "<li><a href=\"./disabled-users.php\" class=\"menu-btn\">Disabled Users</a></li>";
}
?>
<li><a href="listing-cities.php" class="menu-btn">Search</a></li>
<?php
//Shows only when the user is not logged-in
if (!isset($_SESSION['loggedin']))
{
echo "<li><a href=\"login.php\" class=\"menu-btn\">Login</a></li>
<li><a href=\"register.php\" class=\"menu-btn\">Register</a></li>";
}
?>
<?php
//Shows for logged in users
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true)
{
echo "<li><a href=\"./user-update.php\">Edit Profile</a></li>";
echo "<li><a href=\"./user-password.php\">Change Password</a></li>";
echo "<li><a href=\"./logout.php\">Log Out</a></li>";
}
?>
</ul>
<div class="menu-btn">
<i class="fas fa-bars"></i>
</div>
</div>
</nav>
<file_sep>SELECT * FROM favourites<file_sep>--Group 13
--purchase_type.sql
--October 19, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS purchase_type;
--Creates the table again
CREATE TABLE purchase_type(
value INT PRIMARY KEY,
property VARCHAR(30) NOT NULL
);
--Inserts rows inside the table
INSERT INTO purchase_type (value, property) VALUES (1, 'For Sale');
INSERT INTO purchase_type (value, property) VALUES (2, 'For Rent');
<file_sep>--Group 13
--listings.sql
--October 19, 2016
--WEBD3201
drop sequence if exists listing_id_seq;
--autoincrement an identifier every time a record is inserted
create sequence listing_id_seq;
select setval('listing_id_seq', 10000);
--Creates the listings table
CREATE TABLE listings(
listing_id INTEGER PRIMARY KEY DEFAULT NEXTVAL('listing_id_seq'),
user_id VARCHAR(20) NOT NULL REFERENCES users(user_id),
status CHAR(1) NOT NULL,
price NUMERIC NOT NULL,
headline VARCHAR(100) NOT NULL,
description VARCHAR(1000) NOT NULL,
postal_code CHAR(6) NOT NULL,
images SMALLINT DEFAULT(0) NOT NULL,
city INTEGER NOT NULL,
property_options INTEGER NOT NULL,
bedrooms INTEGER NOT NULL,
bathrooms INTEGER NOT NULL,
garage INTEGER DEFAULT(0) NOT NULL,
purchase_type INTEGER DEFAULT(0) NOT NULL,
property_type INTEGER DEFAULT(0) NOT NULL,
finished_basement INTEGER DEFAULT(0) NOT NULL,
open_house INTEGER DEFAULT(0) NOT NULL,
schools INTEGER DEFAULT(0) NOT NULL
);
--Inserts rows inside the table
INSERT INTO people VALUES('realtor','Ms.','Joe','Doe','Magic Land','','','','','1231231234','','','P'); -- testpass
INSERT INTO people VALUES('aladila','Mr.','Amar','Al-Adil','Westney Rd.','','Ajax','ON','L1T2N1','1231231234','','','T'); --amar
INSERT INTO people VALUES('abc','Ms.','Joe','Doe','Magic Land','','','','','1231231234','','','E'); -- 123
INSERT INTO people VALUES('Mandy','Ms.','Joe','Doe','Magic Land','','','','','1231231234','','','P'); --russia<file_sep><?php
/*
Group 13
September 29, 2016
WEBD3201
The listing display page
*/
$title = "Listing Display";
$date = "September 29, 2016";
$filename = "index.php";
$description = "The listing display page for individual houses ";
include("header.php");
?>
<h1> Listing Display </h1>
<hr/>
<table style="width:50%" border="1px solid black">
<tr>
<th>Listing Image</th>
<th>Listing Description</th>
</tr>
<tr>
<th rowspan="2"><img src="Houses/bolmanville.jpg" alt="Oshawa House" width="300px" height="200px"/>
</th>
<td align="left" valign="top">
<h3>Bowmanville home completely finished</h3>
<ul>
<li>Finished Basement</li>
<li>3 Bedrooms</li>
<li>For Sale</li>
<li>Double garage</li>
<li>Main room and basement fireplace</li>
<li>Status: Open</li>
<li>3 Washrooms</li>
<li>Description: Great home if you are interested in moving in without having to spend time and money as it has a finished basement including a washroom down there. </li>
</ul>
</td>
</tr>
<tr>
<td align="left" valign="top"><ul>
<li>Location: Bolmanville</li>
<li>Postal Code: P1W ME4</li>
<li>Price: $600,000</li>
</ul></td>
</tr>
</table>
<form action="search-result.php">
<p>
<input type="submit" name="submit" value="Back to search results "/></p>
</form>
<?php include 'footer.php'; ?><file_sep>--Group 13
--people.sql
--October 11, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS people;
--Creates the table again
/*
salutation: an VARCHAR that can hold up to 10 characters (can be empty)
first_name: a VARCHAR that can hold up to 25 characters (cannot be empty)
last_name: a VARCHAR that can hold up to 50 characters (cannot be empty)
street_address_1: a VARCHAR that can hold up to 75 characters (can be empty)
street_address_2: a VARCHAR that can hold up to 75 characters (can be empty)
city: a VARCHAR that can hold up to 75 characters (can be empty)
province: a VARCHAR that can hold up to 2 characters (can be empty)
postal_code: a VARCHAR that can hold up to 6 characters (can be empty)
primary_phone_number: a VARCHAR that can hold up to 15 characters (cannot be empty)
secondary_phone_number: a VARCHAR that can hold up to 10 characters (can be empty)
fax_number: a VARCHAR that can hold up to 10 characters (can be empty)
preferred_contact_method: a CHAR that can hold up to 1 character (cannot be empty)
*/
CREATE TABLE people(
user_id VARCHAR(20) REFERENCES users(user_id) NOT NULL,
salutation VARCHAR(10),
first_name VARCHAR(25) NOT NULL,
last_name VARCHAR(50) NOT NULL,
street_address_1 VARCHAR(75),
street_address_2 VARCHAR(75),
city VARCHAR(75),
province VARCHAR(2),
postal_code VARCHAR(6),
primary_phone_number VARCHAR(15) NOT NULL,
secondary_phone_number VARCHAR(10),
fax_number VARCHAR(10),
preferred_contact_method CHAR(1) NOT NULL
);
/*
--Inserts rows inside the table
INSERT INTO people VALUES('realtor','179ad45c6ce2cb97cf1029e212046e81','R','<EMAIL>','2016-1-1','2016-2-1'); -- testpass
INSERT INTO people VALUES('aladila','36341cbb9c5a51ba81e855523de49dfd','R','<EMAIL>','2016-3-13','2016-3-22'); --amar
INSERT INTO people VALUES('abc','202cb962ac59075b964b07152d234b70','R','<EMAIL>','2016-3-22','2016-3-4'); -- 123
INSERT INTO people VALUES('Mandy','1c625cc86f824660a320d185916e3c55','R','<EMAIL>','2016-4-20','2016-3-4'); --russia
*/
<file_sep>-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS listings;
<file_sep>--Group 13
--favourite.sql
--December 1, 2016
--WEBD3201
-- Dropping tables clear out any existing data
DROP TABLE IF EXISTS favourites;
--Creates the table again
CREATE TABLE favourites(
user_id VARCHAR(20) REFERENCES users(user_id) NOT NULL,
listing_id INTEGER REFERENCES listings(listing_id) NOT NULL
);
/*
user_id: a varchar that can hold 20 characters (Make this so it cannot be NULL, and should have a corresponding record in the users table. i.e. make user_id in favourites a FOREIGN KEY).
This is the user that wants to track the specific listing, and they have to already exist as a user in the system.
listing_id: an INTEGER (Make this so it cannot be NULL, and should have a corresponding record in the listings table. i.e. make listing_id in favourites a FOREIGN KEY).
This is the listing that the users wants to track, and the listing has to exist as a user in the system.
*/<file_sep><?php
/*
Group_13
September 29, 2016
WEBD3201
Log-out page
*/
$title = "Login";
$date = "September 29, 2016";
$filename = "login.php";
$description = "The login page ";
include("header.php");
?>
<?php
session_destroy();
header("Location: login.php");
?>
<?php include 'footer.php'; ?>
<file_sep><?php
/*
Group 13
September 29, 2016
WEBD3201
The listing display page
*/
$title = "Listing Display";
$date = "September 29, 2016";
$filename = "index.php";
$description = "The listing display page for individual houses ";
include("header.php");
?>
<h1> Listing Display </h1>
<hr/>
<table style="width:50%" border="1px solid black">
<tr>
<th>Listing Image</th>
<th>Listing Description</th>
</tr>
<tr>
<th rowspan="2"><img src="Houses/pickering.JPG" alt="Pickering House" width="300px" height="200px"/>
</th>
<td align="left" valign="top">
<h3>Pickering home perfect for two people</h3>
<ul>
<li>Duplex</li>
<li>For Rent or Sale</li>
<li>Open House</li>
<li>Corner Lot</li>
<li>Status: Open</li>
<li>2 Washrooms</li>
<li>2 Bedrooms</li>
<li>Description: Ideal home for someone not looking to climb flights of stairs everyday but still have the space for needs in a house. Open to buy or rent.</li>
</ul>
</td>
</tr>
<tr>
<td align="left" valign="top"><ul>
<li>Location: Pickering</li>
<li>Postal Code: C7C G8F</li>
<li>Price: $300,000</li>
</ul></td>
</tr>
</table>
<form action="search-result.php">
<p>
<input type="submit" name="submit" value="Back to search results "/></p>
</form>
<?php include 'footer.php'; ?><file_sep><!--
Programmer: Group_13
Program Name: <?php echo $filename; ?>
Date: <?php echo $date; ?>
Purpose: <?php echo $description; ?>
-->
<?php session_start();
require("./includes/constants.php");
require("./includes/functions.php");
require("./includes/db.php");
ob_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="shortcut icon" href="images/LogoFinal_Icon.ico" />
<link rel="stylesheet" type="text/css" href="css/webd3201.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $title; ?> </title>
</head>
<body class="text-color">
<div id="container">
<div id="header">
<img src="images/LogoFinal2.png" alt="Web Logo" width="500" height="128"/>
<h1><?php echo WEBSITE_NAME; ?></h1>
</div>
<div id="sites">
<ul>
<li><a href="./index.php">Home Page</a></li>
<?php
//Shows only when the user is not logged-in
if (!isset($_SESSION['loggedin']))
{
echo "<li><a href=\"./login.php\">Login</a></li>";
echo "<li><a href=\"./register.php\">Register</a></li>";
echo "<li><a href=\"./password-request.php\">Password Request</a></li>";
}
?>
<?php
//Shows only for CLIENTS
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['user_type'] == GET_USER)
{
echo "<li><a href=\"./welcome.php\">Welcome</a></li>";
}
//Shows only for AGENTS
else if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['user_type'] == GET_AGENT)
{
echo "<li><a href=\"./dashboard.php\">Dashboard</a></li>";
echo "<li><a href=\"./listing-create.php\">List Create</a></li>";
}
//Shows only for ADMIN
else if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['user_type'] == GET_ADMIN)
{
echo "<li><a href=\"./admin.php\">Admin</a></li>";
echo "<li><a href=\"./disabled-users.php\">Disabled Users</a></li>";
}
?>
<!--<li><a href="./listing-create.php">List Create</a></li>-->
<li><a href="./listing-cities.php">Search</a></li>
<?php
//Shows for logged in users
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true)
{
echo "<li><a href=\"./user-update.php\">Edit Profile</a></li>";
echo "<li><a href=\"./user-password.php\">Change Password</a></li>";
echo "<li><a href=\"./logout.php\">Log Out</a></li>";
}
?>
</ul>
</div>
<div id="content-container">
<file_sep>This is a real estate website with search funcationality.
Once sellers post their house, they can upload images to showcase the house and interior.
You can test the realtor account with, username=aladila password=<PASSWORD><file_sep><?php
/*
Group 13
September 29, 2016
--WEBD3201
*/
function displayCopyright()
{
echo "JTAS Inc. ". date('Y');
}
function display_phone_number($phone)
{
$phone = preg_replace("/[^0-9]/", "", $phone);
if(strlen($phone) == 7)
{
return preg_replace("/(\d{3})(\d{4})/", "$1-$2", $phone);
}
elseif(strlen($phone) == 10)
{
return preg_replace("/(\d{3})(\d{3})(\d{4})/", "($1) $2-$3", $phone);
}
elseif(strlen($phone) == 15)
{
return preg_replace("/(\d{3})(\d{3})(\d{4})/", "($1) $2-$3 ext.$4", $phone);
}
else
{
return $phone;
}
}
//Got this code from: http://www.pixelenvision.com/1708/zip-postal-code-validation-regex-php-code-for-12-countries/
function is_valid_postal_code($postal)
{
$regex = "^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$";
if (!preg_match("/".$regex."/i",$postal))
{
return true;
} else
{
return false;
}
}
/*
this function should be passed a integer power of 2, and any decimal number,
it will return true (1) if the power of 2 is contain as part of the decimal argument
*/
function isBitSet($power, $decimal) {
if((pow(2,$power)) & ($decimal))
return 1;
else
return 0;
}
/*
this function can be passed an array of numbers (like those submitted as
part of a named[] check box array in the $_POST array).
*/
function sumCheckBox($array)
{
$num_checks = count($array);
$sum = 0;
for ($i = 0; $i < $num_checks; $i++)
{
$sum += $array[$i];
}
return $sum;
}
function makeWhereStatement($table, $selectedValue, $fieldName)
{
$sql = 'SELECT * FROM '.$table;
$result = pg_query(db_connect(), $sql);
$records = pg_num_rows($result);
for($i = 0; $i < $records; $i++)
{
if (isBitSet($i, $selectedValue))
{
if (empty($where) && ($_SESSION['WhereStarted'] == true))//if the choices beforehand wasn't chosen, it would start a where
{
$where = "WHERE";
}
if (!isset($sql_table) && ($_SESSION['WhereStarted'] == true)) //Sets up the where in front of the criterias
{
$sql_table = $where." ($fieldName = ". pg_fetch_result($result, $i, "value"). " ";
}
else if(!isset($sql_table)) //Starts AND, if there options beforhand had WHERE started
{
$sql_table = "AND ($fieldName = ". pg_fetch_result($result, $i, "value"). " ";
}
else if(isset($sql_table)) //adds OR before the next criteria is entered
{
$sql_table .= "OR $fieldName = ". pg_fetch_result($result, $i, "value"). " ";
}
$_SESSION['WhereStarted'] = false;//Makes sure WHERE start once
}
}
if (isset($sql_table))
{
$sql_table .= ") ";
//$sqlPrepare .= $sql_table;
//echo "<br/>$sql_table";
return $sql_table;
}
else
{
return "";
}
}
/*Function to make a random password for password request email*/
function randomPasswordGenerator() {
$charecters = "abcdefghijklmnopqrst<KEY>IJKLMN<KEY>";
$pass = array();
$charectersLength = strlen($charecters) - 1;
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $charectersLength);
$pass[] = $charecters[$n];
}
return implode($pass);
}
?><file_sep>
--Inserts rows inside the table
INSERT INTO people VALUES('realtor','Ms.','Joe','Doe','Magic Land','','','','','1231231234','','','P'); -- testpass
INSERT INTO people VALUES('aladila','Mr.','Amar','Al-Adil','Westney Rd.','','Ajax','ON','L1T2N1','1231231234','','','T'); --amar
INSERT INTO people VALUES('abc','Ms.','Joe','Doe','Magic Land','','','','','1231231234','','','E'); -- 123
INSERT INTO people VALUES('Mandy','Ms.','Joe','Doe','Magic Land','','','','','1231231234','','','P'); --russia
<file_sep><?php
/*
Group 13
September 29, 2016
WEBD3201
The Welcome Page
*/
$title = "Welcome";
$date = "September 29, 2016";
$filename = "index.php";
$description = " A page that welcomes the agent";
include("header.php");
?>
<?php
//Current Max Listings
$CurrentListNumber = pg_num_rows(pg_query("Select * from listings"));
echo "<br>Current rows in listings: ".$CurrentListNumber."<br><br>";
//Current Agents availiable
$AgentList = array();
//---------------------------------------------------------------------------------USER ID
$result = pg_query("SELECT user_id FROM users WHERE user_type = 'R';");
while ($row = pg_fetch_assoc($result)) {
$AgentList = array_merge($AgentList, array_map('trim', explode(",", $row['user_id'])));
}
print_r(array_values($AgentList));
echo "<br/><br/>Number of Agents: ".count($AgentList);
//----------------------------------------------------------------------------------------STATUS
$status = array();
$result = pg_query("SELECT value FROM listing_status");
while ($row = pg_fetch_assoc($result)) {
$status = array_merge($status, array_map('trim', explode(",", $row['value'])));
}
echo "<br><br>Listing Status: ";
print_r(array_values($status));
//----------------------------------------------------------------------------------------------POSTAL CODE
$postalLetters = Array("A","B","C","E","G","H","J","K","L","M","N","P","R","S","T","V","X","Y");
$postal_prefix = Array(
"Ajax" => Array("L1S", "L1T", "L1Z"),
"Bowmanville" => Array("L1B", "L1C", "L1E"),
"Brooklin" => "L1M",
"Oshawa" => Array("L1G", "L1H", "L1J", "L1K", "L1L"),
"Pickering" => Array("L1V", "L1W", "L1X", "L1Y"),
"Port Perry" => "L9L",
"Whitby" => Array("L1V", "L1W", "L1X", "L1Y")
);
echo "<br><br>Postal Prefix: ";
print_r($postal_prefix);
//-------------------------------------------------------------------------------------CITY
$city = array();
$result = pg_query("SELECT * FROM cities");
while ($row = pg_fetch_assoc($result)) {
$city = array_merge($city, array_map('trim', explode(",", $row['value'])));
}
echo "<br><br>City: ";
print_r(array_values($city));
//-----------------------------------------------------------------------------------OPTIONS
$options = array();
$result = pg_query("SELECT * FROM property_options");
while ($row = pg_fetch_assoc($result)) {
$options = array_merge($options, array_map('trim', explode(",", $row['value'])));
}
echo "<br><br>Options: ";
print_r(array_values($options));
//-----------------------------------------------------------------------------------BEDS
$bedrooms = array();
$result = pg_query("SELECT * FROM bedrooms");
while ($row = pg_fetch_assoc($result)) {
$bedrooms = array_merge($bedrooms, array_map('trim', explode(",", $row['value'])));
}
echo "<br><br>Bedroom: ";
print_r(array_values($bedrooms));
//echo "<br>" . $bedrooms[rand(0,count($bedrooms)-1)];
//-----------------------------------------------------------------------------------BATHS
$washrooms = array();
$result = pg_query("SELECT * FROM washrooms");
while ($row = pg_fetch_assoc($result)) {
$washrooms = array_merge($washrooms, array_map('trim', explode(",", $row['value'])));
}
echo "<br><br>Washroom: ";
print_r(array_values($washrooms));
//-----------------------------------------------------------------------------------GARAGE
$garage = array();
$result = pg_query("SELECT * FROM garage_type");
while ($row = pg_fetch_assoc($result)) {
$garage = array_merge($garage, array_map('trim', explode(",", $row['value'])));
}
echo "<br><br>Garage: ";
print_r(array_values($garage));
//-----------------------------------------------------------------------------------PURCHASE TYPE
$purchase_type = array();
$result = pg_query("SELECT * FROM purchase_type");
while ($row = pg_fetch_assoc($result)) {
$purchase_type = array_merge($purchase_type, array_map('trim', explode(",", $row['value'])));
}
echo "<br><br>purchase_type: ";
print_r(array_values($purchase_type));
//-----------------------------------------------------------------------------------PURCHASE TYPE
$property_type = array();
$result = pg_query("SELECT * FROM property_type");
while ($row = pg_fetch_assoc($result)) {
$property_type = array_merge($property_type, array_map('trim', explode(",", $row['value'])));
}
echo "<br><br>property_type: ";
print_r(array_values($property_type));
//-----------------------------------------------------------------------------------BASEMENT
$finished_basement = array();
$result = pg_query("SELECT * FROM finished_basement");
while ($row = pg_fetch_assoc($result)) {
$finished_basement = array_merge($finished_basement, array_map('trim', explode(",", $row['value'])));
}
echo "<br><br>finished_basement: ";
print_r(array_values($finished_basement));
//-----------------------------------------------------------------------------------OPEN HOUSE?
$open_house = array();
$result = pg_query("SELECT * FROM open_house");
while ($row = pg_fetch_assoc($result)) {
$open_house = array_merge($open_house, array_map('trim', explode(",", $row['value'])));
}
echo "<br><br>open_house: ";
print_r(array_values($open_house));
//-----------------------------------------------------------------------------------SCHOOLS
$schools = array();
$result = pg_query("SELECT * FROM schools");
while ($row = pg_fetch_assoc($result)) {
$schools = array_merge($schools, array_map('trim', explode(",", $row['value'])));
}
echo "<br><br>schools: ";
print_r(array_values($schools));
/*
open_house INTEGER DEFAULT(0) NOT NULL,
schools INTEGER DEFAULT(0) NOT NULL
*/
echo "<br>";
//------------------------------------------------------------------------------------START LOOP
$getID = $CurrentListNumber;
for ($x = 0; $x <= 1500; $x++)
{
$getAgent = $AgentList[rand(0,count($AgentList)-1)];
$getStatus = $status[rand(0,count($status)-1)];
$getHeadline = "";
$getDescripion = "";
$getPostal = "";
$getImage = rand(1,10000);
$getCity = "";
$getOptions = "";
$getBed = "";
$getBath = "";
$getGarage = "";
$getPurchase = "";
$getProperty = "";
$getBasement = "";
$getHouse = "";
$getSchools = "";
$getCity = $city[rand(0,count($city)-1)];
//To get the area code of the Postal CODE
if ($getCity == 1)//AJAX
{
$getPostal = $postal_prefix['Ajax'][rand(0,2)];
}
elseif ($getCity == 2)//Bowmanville
{
$getPostal = $postal_prefix['Bowmanville'][rand(0,2)];
}
elseif ($getCity == 4)//Brooklin
{
$getPostal = $postal_prefix['Brooklin'];
}
elseif ($getCity == 8)//Oshawa
{
$getPostal = $postal_prefix['Oshawa'][rand(0,4)];
}
elseif ($getCity == 16)//Pickering
{
$getPostal = $postal_prefix['Pickering'][rand(0,3)];
}
elseif ($getCity == 32)//Port Perry
{
$getPostal = $postal_prefix['Port Perry'];
}
elseif ($getCity == 64)//Whitby
{
$getPostal = $postal_prefix['Whitby'][rand(0,3)];
}
//----------------------------------------------------------------------------Postal Code Last three code
for ($code = 1; $code <= 3; $code++)
{
if ($code % 2 == 0)
{
$getPostal .= $postalLetters[rand(0,(count($postalLetters)-1))];
}
else
{
$getPostal .= rand(0,9);
}
}
$getPrice = rand(100000,1000000);
$getOptions = $options[rand(0,count($options)-1)];
$getBed = $bedrooms[rand(0,count($bedrooms)-1)];
$getBath = $washrooms[rand(0,count($washrooms)-1)];
$getGarage = $garage[rand(0,count($garage)-1)];
$getPurchase = $purchase_type[rand(0,count($purchase_type)-1)];
$getProperty = $property_type[rand(0,count($property_type)-1)];
$getBasement = $finished_basement[rand(0,count($finished_basement)-1)];
$getHouse = $open_house[rand(0,count($open_house)-1)];
$getSchools = $schools[rand(0,count($schools)-1)];
$rand = rand(0,3);
if ($rand == 0)
{
$getHeadline = "".get_property('property_type',$getProperty). " in " . get_property('cities',$getCity). " is ". get_property('purchase_type',$getPurchase);
}
else if($rand == 1)
{
$getHeadline = "A ".get_property('property_type',$getProperty)." in ".get_property('cities',$getCity).", Ontario ". $getPostal;
}
else if($rand == 2)
{
$getHeadline = "". get_property('purchase_type',$getPurchase)." ".get_property('property_type',$getProperty)." in ".get_property('cities',$getCity)." ".$getPostal;
}
else
{
$getHeadline = "".get_property('purchase_type',$getPurchase).": a ".get_property('property_type',$getProperty). " in " . get_property('cities',$getCity);
}
$result = pg_query("SELECT * FROM people where user_id = '". $getAgent ."';");
$getContact = pg_query("SELECT * FROM people where user_id = '". $getAgent ."';");
$getDescripion = "Agent: ". pg_fetch_result($result, 0, "first_name")." ".pg_fetch_result($result, 0, "last_name") ." Bedroom: ".get_property('bedrooms',$getBed). "\t\t Bathroom: ".get_property('washrooms',$getBath)." Building type: ".get_property('property_type',$getProperty)."\n Please contact by: ". get_property('contact_method',pg_fetch_result($result, 0, "preferred_contact_method"));
echo "<br>";
echo "<br>List ID: ". $getID;
echo "<br>Agent's name: ". $getAgent;
echo "<br>Listing Status: ". get_property('listing_status',$getStatus);
echo "<br>Price: " . number_format($getPrice,2);
echo "<br/>Headline: ". $getHeadline;
echo "<br/>Description: ". $getDescripion;
echo "<br/>Postal: ". $getPostal;
echo "<br/>Image: ". $getImage;
echo "<br/>City: ".get_property('cities',$getCity);
echo "<br/>Property Options: ". get_property('property_options',$getOptions);
echo "<br/>Bedroom: ". get_property('bedrooms',$getBed);
echo "<br/>Bathroom: ". get_property('washrooms',$getBath);
echo "<br/>Garage: ". get_property('garage_type',$getGarage);
echo "<br/>Purchase Type: ". get_property('purchase_type',$getPurchase);
echo "<br/>Property Type: ". get_property('property_type',$getProperty);
echo "<br/>Basement?: ". get_property('finished_basement',$getBasement);
echo "<br/>Open House?: ". get_property('open_house',$getHouse);
echo "<br/>Schools nearby: ". get_property('schools',$getSchools);
echo "<hr>";
pg_execute(db_connect(),"insert_listings",array($getID, $getAgent, strtoupper($getStatus), $getPrice, $getHeadline, $getDescripion, strtoupper($getPostal), $getImage, $getCity, $getOptions, $getBed, $getBath, $getGarage, $getPurchase, $getProperty, $getBasement, $getHouse, $getSchools) );
//echo "<br>".$sql;
//pg_query(db_connect(), $sql);
//Increments for the listings table as they need to be unique
$getID = $getID + 1;
}
?>
<?php include 'footer.php'; ?><file_sep><?php
/*
Group 13
November 24, 2016
WEBD3201
The listing update page
*/
$title = "Listing Update";
$date = "November 24, 2016";
$filename = "listing-update.php";
$description = "The Listing update page which update the listings information ";
include("header.php");
?>
<?php
$error = "";
$output = "";
//Gets the actual link
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
//Gets all of the values where the listing id matches
$listing_id = (isset($_GET['listing_id']))? $_GET['listing_id']: 0;
$sql = "SELECT * FROM listings WHERE listing_id=$listing_id";
$query = pg_execute(db_connect(), "get_listing",array($listing_id));
if (!isset($_SESSION['loggedin']))
{
header("Location: login.php");
ob_flush();
}
if(isset($_SESSION['user_type']))
{
if ($_SESSION['user_type'] == GET_USER)
{
header("Location: welcome.php");
ob_flush();
}
//If logged in user is not the same as the listing creator
else if ($_SESSION['username'] != pg_fetch_result($query, 0, "user_id"))
{
header("Location: dashboard.php");
}
}
if($_SERVER["REQUEST_METHOD"] == "GET")
{
//default mode when the page loads the first time
//can be used to make decisions and initialize variables
//ROW 1
$beds = pg_fetch_result($query, 0, "bedrooms");
$wash = pg_fetch_result($query, 0, "bathrooms");
$open = pg_fetch_result($query, 0, "open_house");
$basement = pg_fetch_result($query, 0, "finished_basement");
//ROW 2
$purchase = pg_fetch_result($query, 0, "purchase_type");
$extraoptions = pg_fetch_result($query, 0, "property_options");
$garage = pg_fetch_result($query, 0, "garage");
//ROW 3
$schools = pg_fetch_result($query, 0, "schools");
$status = strtolower(pg_fetch_result($query, 0, "status"));
$cities = pg_fetch_result($query, 0, "city");
$headline = pg_fetch_result($query, 0, "headline");
//ROW 4
$info = pg_fetch_result($query, 0, "description");
$price = pg_fetch_result($query, 0, "price");
$postal = pg_fetch_result($query, 0, "postal_code");
$property = pg_fetch_result($query, 0, "property_type");
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
//When upload page is uploaded
if (isset($_POST['upload']))
{
header("Location: listing-images.php?submit=Search+source+code&listing_id=$listing_id");
}
//the page got here from submitting the form, let's try to process
//ROW 1
$beds = trim($_POST["bedrooms"]);
$wash = trim($_POST["washrooms"]);
if (isset($_POST['open_house'])){ $open = ($_POST["open_house"]); }else{ $open = ""; }
if (isset($_POST['finished_basement'])){ $basement = ($_POST["finished_basement"]); }else{$basement = "";}
//ROW 2
$purchase = ($_POST["purchase_type"]);
$extraoptions = ($_POST["property_options"]);
$garage = ($_POST['garage_type']);
if ( isset($_POST['schools'])){ $schools = ($_POST['schools']); }else{ $schools = ""; }
if ( isset($_POST['listing_status'])){ $status = ($_POST['listing_status']); }else{$status = "";}
$cities = ($_POST['cities']);
$headline = trim($_POST['headline']);
$info = trim($_POST['description']);
$price = trim($_POST['price']);
$postal = trim($_POST['postal']);
$property = ($_POST["property_type"]);
//If the submit button was clicked
if (isset($_POST["submit"] ) )
{
//bedrooms validation
if(!isset($beds) || $beds == "")
{
//means the user did not enter anything
$error .= "Select how many bedrooms. <br/>";
}
//washrooms validation
if(!isset($wash) || $wash == "")
{
//means the user did not enter anything
$error .= "Select how many washrooms. <br/>";
}
//open house validation
if(!isset($open) || $open == "")
{
//means the user did not enter anything
$error .= "Select an open house option. <br/>";
}
//finished basement validation
if(!isset($basement) || $basement == "")
{
//means the user did not enter anything
$error .= "Select a basement option. <br/>";
}
//purchase type validation
if(!isset($purchase) || $purchase == "")
{
//means the user did not enter anything
$error .= "Select the type of purchase. <br/>";
}
//price validation
if(!isset($price) || $price == "")
{
//means the user did not enter anything
$error .= "Price cannot be empty. <br/>";
}
else if (!is_numeric($price))
{
$error .= "Price must be numeric. <br/>";
}
//house type validation
if(!isset($property) || $property == "")
{
//means the user did not enter anything
$error .= "Select the type of house. <br/>";
}
//garage validation
if(!isset($garage) || $garage == "")
{
//means the user did not enter anything
$error .= "Select the type of garage. <br/>";
}
//description validation
if(!isset($info) || $info == "")
{
//means the user did not enter anything
$error .= "Description cannot be empty. <br/>";
}
//headline validate
if(!isset($headline) || $headline == "")
{
//means the user did not enter any dap
$error .= "Headline cannot be empty. <br/>";
}
//Extra options validation
if(!isset($extraoptions) || $extraoptions == "")
{
//means the user did not enter anything
$error .= "Select a Property Option. <br/>";
}
//status validation
if(!isset($status) || $status == "")
{
//means the user did not enter anything
$error .= "Select a status of the listing. <br/>";
}
//school validation
if(!isset($schools) || $schools == "")
{
//means the user did not enter anything
$error .= "Select if the listing is near any schools. <br/>";
}
//postal code validation
if(!isset($postal) || $postal == "")
{
//means the user did not enter anything
$error .= "Postal Code cannot be empty. <br/>";
}
else if (is_valid_postal_code($postal))
{
$error .= "Postal Code (".$postal.") is not a valid Postal Code<br/>";
$postal = "";
}
//city validation
if(!isset($cities) || $cities == "")
{
//means the user did not enter anything
$error .= "Select a city. <br/>";
}
//if error is an empty string
if($error == "")
{
/* echo "<br/>User ID: ".$_SESSION['username'];
echo "<br/>Status: ". strtoupper($status);
echo "<br/>Price: " .$price;
echo "<br/>Headline: ".$headline;
echo "<br/>Description: ".$info;
echo "<br/>Postal Code: ".strtoupper($postal);
echo "<br/>Image: ". $image = 1;
echo "<br/>City: ".$cities;
echo "<br/>Property Option: ".$extraoptions;
echo "<br/>Bathroom: ". $wash;
echo "<br/>Garage: ". $garage;
echo "<br/>Purchase Type: ". $purchase;
echo "<br/>Property Type: ". $property;
echo "<br/>Finished Basement: ". $basement;
echo "<br/>Open House: ". $open;
echo "<br/>Schools: ". $schools;*/
$total_row = pg_num_rows( pg_query(db_connect(), 'select * from listings') );
pg_execute(db_connect(),"update_listings",array(strtoupper($status), $price, $headline, $info, strtoupper($postal), $cities, $extraoptions, $beds, $wash, $garage, $purchase, $property, $basement, $open, $schools, $listing_id) );
$output = "The Listing Has Been Updated";
}
}
/*
0
Notice: Undefined variable: image in C:\Users\Troll\Desktop\Durham College\Semester 3\WEBD\GROUP\listing-create.php on line 220
Warning: pg_execute() [function.pg-execute]: Query failed: ERROR: null value in column "images" violates not-null constraint DETAIL: Failing row contains (0, aladila, O, 223, COOL, aaaaw, L1T2N1, null, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1). in C:\Users\Troll\Desktop\Durham College\Semester 3\WEBD\GROUP\listing-create.php on line 220
*/
}
?>
<section class="content-body" id='formSetup'>
<div class="max-width body-place">
<h2 class="title">Listing Update</h2>
<form action="<?php echo $actual_link; ?>" method="post" >
<h2 style="text-align: center;"><?php echo $output; ?></h2>
<h3 style="text-align: center;"><?php echo $error; ?></h3>
<h3 style="text-align: center;">[ Inputs must not be empty when editting. ]</h3>
<br/>
<div class="otherForm">
<?php
$table = 'bedrooms';
echo build_simple_dropdown($table, $beds);
?>
<label>Number of bedrooms:</label>
</div>
<div class="otherForm">
<?php
$table = 'washrooms';
echo build_dropdown($table, $wash);
?>
<label>Number of Washrooms:</label>
</div>
<div class="radioForm">
<div>
Open House?:
</div>
<?php
$table = 'open_house';
echo build_radio($table, $open);
?>
</div>
<div class="radioForm">
<div>
Finished basement?:
</div>
<?php
$table = 'finished_basement';
echo build_radio($table, $open);
?>
</div>
<div class="otherForm">
<?php
$table = 'purchase_type';
echo build_dropdown($table, $purchase);
?>
<label>Type of Listing:</label>
</div>
<div class="input-field">
<input type="text" name="price" value="<?php echo $price; ?>" size="30" />
<label>Price:</label>
</div>
<div class="otherForm">
<?php
$table = 'property_type';
echo build_dropdown($table, $property);
?>
<label>Type of House:</label>
</div>
<div class="otherForm">
<?php
$table = 'garage_type';
echo build_dropdown($table, $garage); ?>
<label>Garage Type:</label>
</div>
<div class="otherForm">
<input type="submit" name="upload" value="Upload Page" />
<label> Current Image: <?php echo pg_fetch_result($query, 0, "images"); ?></label>
</div>
<div class="otherForm">
<textarea name = "description" rows="4" cols="30"><?php echo htmlspecialchars($info);?></textarea>
<label>Description:</label>
</div>
<div class="input-field">
<input type="text" name="headline" value="<?php echo $headline; ?>" size="30" />
<label>Headline:</label>
</div>
<div class="otherForm">
<?php
$table = 'property_options';
echo build_dropdown($table, $extraoptions);?>
<label>Property Options:</label>
</div>
<div class="radioForm">
<div>
Status:
</div>
<?php
$table = 'listing_status';
echo build_radio($table, $status);
?>
</div>
<div class="radioForm">
<div>
Near a School:
</div>
<?php
$table = 'schools';
echo build_radio($table, $schools);
?>
</div>
<div class="input-field">
<input type="text" name="postal" value="<?php echo $postal; ?>" size="30" />
<label>Postal Code:</label>
</div>
<div class="otherForm">
<?php
$table = 'cities';
echo build_dropdown($table, $cities);
?>
<label>City:</label>
</div>
<input type="submit" name="submit" value="Update Listing"/>
</form>
</div>
</section>
<?php include 'footer.php'; ?><file_sep><?php
/*
Group 13
November 25, 2016
WEBD3201
The image upload page, so user can upload their own photos for the listing
*/
$title = "Image Upload Page";
$date = "November 25, 2016";
$filename = "listing-matches.php";
$description = "Image Upload page where they can upload JPG images to the server ";
include("header.php");
?>
<?php
$error = "";
$output = "";
//Gets the actual link
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
//Gets the listing Id value
$list_id = (isset($_GET['listing_id']))? $_GET['listing_id']: 0;
//Makes the sql query
$sql = "SELECT * FROM listings WHERE listing_id=$list_id";
$result = pg_execute(db_connect(), "get_listing",array($list_id));
if (!isset($_GET['listing_id']) )
{
header("Location: index.php");
}
//If the user logged in does not match the user who created the listing
if ($_SESSION['username'] != pg_fetch_result($result, 0, "user_id"))
{
header("Location: dashboard.php");
}
//Folder location
$dirname = "./listing/$list_id/";
//Gets any images in folder
$images = glob($dirname."*");
//If there are any message sessions created
if (isset($_SESSION['imageMessage']))
{
$output .= $_SESSION['imageMessage'];
unset($_SESSION['imageMessage']);
}
$filecount = 0;
//Check the amount of images in listing
if ($images)
{
$filecount = count($images);
}
//Checks listing image limit
if ($filecount >= IMAGE_AMOUNT_LIMIT)
{
$error .= "<BR>Please delete image/images to be able to upload, be below ".IMAGE_AMOUNT_LIMIT." images.";
}
//When user enters the page
if($_SERVER["REQUEST_METHOD"] == "GET")
{
//echo UPLOAD_ERR_OK;
}
//When someone clicks to upload
if(isset($_POST["submit"]))
{
$target_dir = $dirname;
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
// Check if image file is a actual image or fake image
if($check !== false)
{
//echo "<BR>File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$error .= "<BR>File is not an image.";
$uploadOk = 0;
}
//Checks listing image limit
if ($filecount >= IMAGE_AMOUNT_LIMIT)
{
$uploadOk = 0;
}
if ($_FILES["fileToUpload"]["name"] == "")
{
$error .= "<BR>Cannot upload empty file.";
}
// Check if file already exists
else if (file_exists($target_file)) {
$error .= "<BR>Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > IMAGE_SIZE_LIMIT) {
$error .= "<BR>Sorry, your file is too large, must be below ".IMAGE_SIZE_LIMIT ." bytes.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" ) {
$error .= "<BR>Sorry, only JPG file are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0 || $_FILES['file']['error'] != UPLOAD_ERR_OK) {
$error .= "<br/>Please choose an image that matches our requirement.";
// if everything is ok, try to upload file
}
else
{
//If folder does not exist, then it will make it for the user
if (!is_dir($target_dir))
{
mkdir("$target_dir", 0777);
}
//If the website allows the file to be moved, then it will be true
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo "<BR>Permissions: ".chmod("$target_dir".$_FILES["fileToUpload"]["name"], 0777)."";
echo "<BR>code: chmod(\"$target_dir". $_FILES["fileToUpload"]["name"].", 0777).";
//Changes permission
chmod("$target_dir".$_FILES["fileToUpload"]["name"], 0777);
$filecount = 0;
if ($images){
$filecount = count($images) +1;
echo $filecount;
}
$trust = true;
$newName = $target_dir ."".$list_id."_". $filecount.".jpg";
echo $newName;
$i = 1;
//Loops until it finds the right name to rename file as
do {
echo "<BR>Loop $i";
$newName = $target_dir ."".$list_id."_". $i.".jpg";
if (file_exists($newName) )
{
$i +=1;
}
else
{
rename("$target_dir".$_FILES["fileToUpload"]["name"], $newName);
$trust = false;
}
} while ($trust);
$_SESSION['imageMessage'] = "<BR>The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
header("Location: $actual_link");
} else {
//If file was not able to be moved
$error .= "<BR>Sorry, there was an error uploading your file.";
}
}
}
if (isset($_POST['rdoMain']) )
{
$mainValue = $_POST['rdoMain'];
}
else
{
$mainValue = (pg_fetch_result($result, 0, "images") != 0) ? pg_fetch_result($result, 0, "images"): 0;
}
if (isset($_POST["save"]))
{
//UPDATE listings SET images=0 WHERE listing_id=1484
pg_execute(db_connect(),"update_image",array($mainValue, $list_id));
$output = "Main Image Saved";
}
//____________________________________________Delete Functionality
if (isset($_POST["delete"]))
{
$output .= "Delete Clicked";
if (isset($_POST['imageSet']) )
{
$filesDeleted = $_POST['imageSet'];
foreach ($filesDeleted as $file)
{
echo "<br>File selected: ".$file;
if(file_exists($file))
{
unlink($file);
echo "<br>Delete file";
}
$filecount = 0;
if ($images)
{
$filecount = count($images);
$filecount -= count($filesDeleted);
}
}
//Removes the file if there is no more files in the folder
if ($filecount <= 0)
{
rmdir($dirname);
}
$_SESSION['imageMessage'] = "Files deleted successfully.";
header("Location: $actual_link");
}
}
if (isset($_POST["goBack"]))
{
header("Location: listing-update.php?submit=Search+source+code&listing_id=$list_id");
}
?>
<section class="content-body" id='formSetup'>
<div class="max-width body-place">
<h2 class="title">Image Upload</h2>
<h2 style="text-align: center;"><?php echo $output; ?></h2>
<h3 style="text-align: center;"><?php echo $error; ?></h3>
<form id="uploadform" enctype="multipart/form-data" method="post" action="<?php echo $actual_link; ?>">
<strong>Select image for upload: </strong>
<input type="file" name="fileToUpload" id="fileToUpload" required/>
<input type="submit" value="Upload Image" name="submit"/>
</form>
<br/><br/>
<form action="<?php echo $actual_link; ?>" method="post" enctype="multipart/form-data">
<input type="submit" value="Set Main Image" name="save">
<input type="submit" value="Delete Chosen Images" name="delete">
<input type="submit" value="Go Back to Update Page" name="goBack">
<?php
echo "<table border=\"1\">";
$i=1;
//Loops any images that has been found
foreach($images as $image) {
if ($i == 1)
{
echo "<tr>";
echo "<th>Image</th><th>Click to delete</th><th>Choose Main Image</th>";
echo "</tr>";
}
//Searchs for the underscore
$testeee = strrpos($image, '_', 0) +1;
//Gets the number infront
$rest = substr($image, $testeee, 1);
echo "\n";
echo "<tr>";
echo "\n\t<td>";
echo '<img src="'.$image.'" width="300px" /><br /> ';
echo "\n\t\t</td>";
echo "\n\t\t<td><input name=\"imageSet[]\" type=\"checkbox\" class=\"select\" value=\"$image\"/></td>";
$check = ($image == "./listing/".$list_id."/".$list_id."_$mainValue.jpg")? "checked": "";
echo "\n\t\t<td><input name=\"rdoMain\" type=\"radio\" class=\"select\" $check value=\"$rest\"/></td>";
echo "\n\t</tr>";
$i +=1;
}
echo "</table>";
echo "</form>
</div>
</section>"
?>
<?php include 'footer.php'; ?><file_sep><?php
/*
Group_13
September 29, 2016
WEBD3201
Register page
*/
$title = "Register";
$date = "September 28, 2016";
$filename = "register.php";
$description = "The register page ";
include("header.php");
?>
<?php
/*
$sql = 'SELECT * FROM contact_method';
$_SESSION['radioSes'] = build_radio($sql);*/
//empty out error and result regardless of method that got you here
$error = "";
$output = "";
//$getContact = $_SESSION['radioSes'];
if($_SERVER["REQUEST_METHOD"] == "GET")
{
//default mode when the page loads the first time
//can be used to make decisions and initialize variables
//User Table Fields
$id = "";
$pass = "";
$vPass = "";
$first = "";
$last = "";
$email = "";
//People Table Fields
$salutation = "";
$provinces = "";
$contact = "";
$street = "";
$secondStreet = "";
$city = "";
$postal = "";
$phone = "";
$secondPhone = "";
$fax = "";
$selected_method = "";
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
//the page got here from submitting the form, let's try to process
$id = trim($_POST["id"]); //the name of the input box on the form, white-space removed
$pass = trim($_POST["pass"]); //the name of the input box on the form, white-space removed
$vPass = trim($_POST["vPass"]); //the name of the input box on the form, white-space removed
$first = trim($_POST["first"]); //the name of the input box on the form, white-space removed
$last = trim($_POST["last"]); //the name of the input box on the form, white-space removed
$email = trim($_POST["email"]); //the name of the input box on the form, white-space removed
$user_type = GET_USER;
//Peoples variables
$salutation = trim($_POST['salutation']);
$street = trim($_POST['street']);
$secondStreet = trim($_POST['2ndStreet']);
$city = trim($_POST['city']);
$provinces = trim($_POST['provinces']);
$postal = trim($_POST['postal']);
$phone = trim($_POST['phone']);
$secondPhone = trim($_POST['2ndPhone']);
$fax = trim($_POST['fax']);
$selected_method = "";
//----------------------------------------------------------------------------------------------USER ID
if(!isset($id) || $id == "")
{
//means the user did not enter anything
$error .= "User ID is empty. <br/>";
}
else if (trim(strlen($id)) < MINIMUM_ID_LENGTH ||strlen($id) > MAXIMUM_ID_LENGTH)
{
$error .= "User ID must be between ".MINIMUM_ID_LENGTH." and ".MAXIMUM_ID_LENGTH." <br/>";
}
else if ( is_user_id($id) == true)
{
$error .= "User ID (".$id.") already taken <br/>";
$id = "";
}
//----------------------------------------------------------------------------------------------PASSWORD
if(!isset($pass) || $pass == "")
{
//means the user did not enter anything
$error .= "Password is empty. <br/>";
}
else if (trim(strlen($pass)) < MINIMUM_PASSWORD_LENGTH ||strlen($pass) > MAXIMUM_PASSWORD_LENGTH)
{
$error .= "Password must be between ".MINIMUM_PASSWORD_LENGTH." and ".MAXIMUM_PASSWORD_LENGTH." <br/>";
$pass = "";
$vPass = "";
}
//----------------------------------------------------------------------------------------------CONFIRM PASSWORD
if (!($pass == $vPass))
{
$error .= "Confirm Password does not match Password. <br/>";
$pass = "";
$vPass = "";
}
//----------------------------------------------------------------------------------------------FIRST NAME
if(!isset($first) || $first == "")
{
//means the user did not enter anything
$error .= "First Name input is empty. <br/>";
}
else if (trim(strlen($first)) > MAX_FIRST_NAME_LENGTH)
{
$error .= "First Name input is more than the ".MAX_FIRST_NAME_LENGTH." limit<br/>";
}
else if (is_numeric($first))
{
$error .= "First Name (".$first.") cannot be a numeric<br/>";
$first = "";
}
//----------------------------------------------------------------------------------------------LAST NAME
if(!isset($last) || $last == "")
{
//means the user did not enter anything
$error .= "Last Name is empty. <br/>";
}
else if (trim(strlen($last)) > MAX_LAST_NAME_LENGTH)
{
$error .= "Last Name input is more than the ".MAX_LAST_NAME_LENGTH." limit <br/>";
}
else if (is_numeric($last))
{
$error .= "Last Name (".$last.") cannot be a numeric<br/>";
$last = "";
}
//----------------------------------------------------------------------------------------------EMAIL
if(!isset($email) || $email == "")
{
//means the user did not enter anything
$error .= "Email is empty. <br/>";
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error .= "Email (".$email.") is not format properly (<EMAIL>) <br/>";
$email = "";
}/*
else if (!eregi("^[_a-z2-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$", $email))
{
$error .= "Email (".$email.") has inappropriate characters (\+\"\'~!([{\/?#$%^&*+=). <br/>";
$email = "";
}
else if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email))
{
$error .= "Email (".$email.") extension is wrong (.com, .ca, .us etc...) <br/>";
$email = "";
}*/
//----------------------------------------------------------------------------------------------USER IS REALTOR OR NOT
if (isset($_POST['realtor']))
{
$user_type = GET_PENDING;
}
//----------------------------------------------------------------------------------------------POSTAL CODE
if(!isset($postal) || !($postal == ""))//if values are entered
{
//means the user did not enter anything
if (trim(strlen($postal)) > MAXIMUM_POSTAL_LENGTH)
{
$error .= "Postal Code cannot be more than ".MAXIMUM_POSTAL_LENGTH." characters <br/>";
}
else if (is_valid_postal_code($postal))
{
$error .= "Postal Code (".$postal.") is not a valid Postal Code<br/>";
$postal = "";
}
}
//----------------------------------------------------------------------------------------------PHONE NUMBER
if( !isset($phone) || $phone == "")//Cannot be null or empty
{
$error .= "Phone number input is empty. <br/>";
}
if(!preg_match('/^[0-9]{3}[0-9]{3}[0-9]{4}$/', $phone))
{
$error .= "\n Phone Number have to have 10 numbers<br/>";
}
else if (substr($phone, 0,3) < MINIMUM_PHONE_LENGTH)
{
$error .= "\n Phone number area code must be ".MINIMUM_PHONE_LENGTH." or more<br/>";
}
else if (substr($phone, 3,3) < MINIMUM_PHONE_LENGTH)
{
$error .= "\n Phone number exchange code must be ".MINIMUM_PHONE_LENGTH." or more<br/>";
}
//----------------------------------------------------------------------------------------------SECOND PHONE NUMBER
if (!isset($secondPhone) || !$secondPhone == "")
{
if(!preg_match('/^[0-9]{3}[0-9]{3}[0-9]{4}$/', $secondPhone))
{
$error .= "\n Phone Number have to have 10 numbers<br/>";
}
else if (substr($secondPhone, 0,3) < MINIMUM_PHONE_LENGTH)
{
$error .= "\n Phone number area code must be ".MINIMUM_PHONE_LENGTH." or more<br/>";
}
else if (substr($secondPhone, 3,3) < MINIMUM_PHONE_LENGTH)
{
$error .= "\n Phone number exchange code must be ".MINIMUM_PHONE_LENGTH." or more<br/>";
}
}
//----------------------------------------------------------------------------------------------FAX NUMBER
if (!isset($fax) || !$fax == "")
{
if(!preg_match('/^[0-9]{3}[0-9]{3}[0-9]{4}$/', $fax))
{
$error .= "\n Phone Number have to have 10 numbers<br/>";
}
else if (substr($fax, 0,3) < MINIMUM_PHONE_LENGTH)
{
$error .= "\n Phone number area code must be ".MINIMUM_PHONE_LENGTH." or more<br/>";
}
else if (substr($fax, 3,3) < MINIMUM_PHONE_LENGTH)
{
$error .= "\n Phone number exchange code must be ".MINIMUM_PHONE_LENGTH." or more<br/>";
}
}
//----------------------------------------------------------------------------------------------CONTACT METHOD
if (isset($_POST['submit']) && isset($_POST['contact_method']))//Sets the variable
{
$selected_method = $_POST['contact_method'];
}
else
{
$error .= "\n Prefered Contact Method cannot be empty";
}
//if error is an empty string
if($error == "")
{
$output = "Successful Registered";
pg_execute(db_connect(),"insert_user",array($id,hash("md5", $pass),$user_type,$email,date("Y-m-d",time()),date("Y-m-d",time()) ) );
pg_execute(db_connect(),"insert_people",array($id,$salutation,$first,$last,$street,$secondStreet,$city,$provinces,$postal,$phone,$secondPhone,$fax,$selected_method) );
header("refresh:5;url=login.php");
ob_flush();
}
}
?>
<h1> Registration Page</h1>
<hr/>
<h2 style="text-align: center;"><?php echo $output; ?></h2>
<h3 style="text-align: center;"><?php echo $error; ?></h3>
<h3 style="text-align: center;">Fill in all Account Information </h3>
<h4 style="text-align: center;"> * means they are required</h4>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table style="border: 1;
background-color: #e5f2ff;
width: auto;
text-align: center;
margin-left: auto;
margin-right: auto;" cellspacing="15">
<tr>
<td colspan="2">
Log-in Information
</td>
</tr>
<tr>
<td align="right">
*Login ID:
</td>
<td><input type="text" name="id" value="<?php echo $id; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td align="right">*Password:
</td>
<td><input type="<PASSWORD>" name="pass" value="" size="30" /> <br/>
</td>
</tr>
<tr>
<td align="right">*Confirm Password:
</td>
<td><input type="password" name="vPass" value="" size="30" /> <br/>
</td>
</tr>
<tr>
<td align="right">*Email:
</td>
<td><input type="text" name="email" value="<?php echo $email; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td align="right">You a Realtor?:
</td>
<td align="left">
<input type="checkbox" name="realtor" value="realtor" <?php echo $out = (isset($_POST['realtor']) == true)? "checked": ""; ?> />
</td>
</tr>
<tr>
<td colspan="2">
Personal Information
</td>
</tr>
<tr>
<td align="right">*First Name:
</td>
<td><input type="text" name="first" value="<?php echo $first; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td align="right">*Last Name:
</td>
<td><input type="text" name="last" value="<?php echo $last; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td align="right">Salutation:
</td>
<td align="left">
<?php
$table = 'salutation';
echo build_simple_dropdown($table, $salutation);
?>
</td>
</tr>
<tr>
<td align="right">Street Name:
</td>
<td><input type="text" name="street" value="<?php echo $street; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td align="right">Second Street:
</td>
<td><input type="text" name="2ndStreet" value="<?php echo $secondStreet; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td align="right">City:
</td>
<td><input type="text" name="city" value="<?php echo $city; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td align="right">Province:
</td>
<td align="left">
<?php
$table = 'provinces';
echo build_simple_dropdown($table, $provinces);
?>
</td>
</tr>
<tr>
<td align="right">Postal Code:
</td>
<td><input type="text" name="postal" value="<?php echo $postal; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td align="right">*Phone Number:
</td>
<td><input type="text" name="phone" value="<?php echo $phone; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td align="right">Second Number:
</td>
<td><input type="text" name="2ndPhone" value="<?php echo $secondPhone; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td align="right">FAX Number:
</td>
<td><input type="text" name="fax" value="<?php echo $fax; ?>" size="30" /> <br/>
</td>
</tr>
<tr>
<td align="right">*Prefered Contact Method:
</td>
<td align="left">
<?php
$table = 'contact_method';
echo build_radio($table,$selected_method)
?>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Register" /></td>
</tr>
</table>
</form>
<br/>
<?php include 'footer.php'; ?>
<file_sep><?php
/*
Group 13
September 29, 2016
WEBD3201
The listing display page
*/
$title = "Listing Display";
$date = "September 29, 2016";
$filename = "index.php";
$description = "The listing display page for individual houses ";
include("header.php");
?>
<h1> Listing Display</h1>
<hr/>
<table style="width:50%" border="1px solid black">
<tr>
<th>Listing Image</th>
<th>Listing Description</th>
</tr>
<tr>
<th rowspan="2"><img src="Houses/ajax.jpg" alt="Oshawa House" width="300px" height="200px"/>
</th>
<td align="left" valign="top">
<h3>Private Ajax home on quiet street</h3>
<ul>
<li>3 Garage Doors</li>
<li>Open House</li>
<li>For Sale</li>
<li>Near an Elementary and Highschool</li>
<li>Status: Open</li>
<li>4 Washrooms</li>
<li>6 Bedrooms</li>
<li>Description: Large driveway to accomodate for cars, and a third garage door to allow space for lawn mowers and extra outdoor machines to keep stored out of the way.</li>
</ul>
</td>
</tr>
<tr>
<td align="left" valign="top"><ul>
<li>Location: Ajax</li>
<li>Postal Code: B9K M8Y</li>
<li>Price: $1,700,000</li>
</ul></td>
</tr>
</table>
<form action="search-result.php">
<p>
<input type="submit" name="submit" value="Back to search results "/></p>
</form>
<?php include 'footer.php'; ?><file_sep><?php
/*
Group 13
September 29, 2016
WEBD3201
The Welcome Page
*/
$title = "Welcome";
$date = "September 29, 2016";
$filename = "index.php";
$description = " A page that welcomes the agent";
include("header.php");
?>
<?php
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$_SESSION['previousPage'] = $actual_link;
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true && $_SESSION['user_type'] == GET_AGENT)
{
if($_SERVER["REQUEST_METHOD"] == "GET")
{
if (isset($_SESSION['ShowMore']) )
{
$check = ($_SESSION['ShowMore']=='checked=true' )? 'checked=true': '';
}
else
{
$check="";
}
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
$check = (isset($_POST['chkShowMore']) )? 'checked=true': '';
$_SESSION['ShowMore'] = $check;
}
echo "<section class=\"content-body result\" id='result'>
<div class=\"max-width body-place\">
<h2 class=\"title\">Welcome to the Agent's area, " . $_SESSION['username'] . "!</h2>
<div class=\"row-info\">";
echo "\n<br/>Password: ".$_SESSION['password']." User Type: ".$_SESSION['user_type']."";
echo "\n<br/>Email: " .$_SESSION['email']. " Enrolled Date: ". $_SESSION['enrol']."";
echo "\n<br/> Last Access: ".$_SESSION['last_access']."";
echo "\n<br/> Personal Information";
echo "\n<br/> Salutation: ".$_SESSION['salutation']."";
echo "\n<br/> First Name: ".$_SESSION['first_name']."";
echo "\n<br/> Last Name: ".$_SESSION['last_name']."";
echo "\n<br/> 1st Street: ".$_SESSION['street_address_1']."";
echo "\n<br/> 2nd Street: ".$_SESSION['street_address_2']."";
echo "\n<br/> City: ".$_SESSION['city']."";
echo "\n<br/> Provinces: ".$_SESSION['province']."";
echo "\n<br/> Primary Phone: ". display_phone_number($_SESSION['primary_phone'])."";
echo "\n<br/> Secondary Phone: ". display_phone_number($_SESSION['secondary_phone'])."";
echo "\n<br/> Fax Number: ". display_phone_number($_SESSION['fax'])."";
echo "\n<br/> Preferred Contact Method: ".$_SESSION['contact_method']."";
$per_page = PAGE_LIMIT;
$start = isset($_GET['start']) ? $_GET['start']: 0;
echo "\n<form action=\"".$_SERVER['PHP_SELF']."\" method=\"post\" >";
echo "<br/><br/><br/><center><input type=\"checkbox\" name=\"chkShowMore\" ".$check." value=\"1\">Show account's closed and hidden listings";
echo "\n<br/><input type=\"submit\" name=\"submit\" value=\"Refresh\"/>";
echo "\n\t</center>";
//If there is session exist, it should put in the value for the checkbox
if (isset($_SESSION['ShowMore']) )
{
$status = ($_SESSION['ShowMore']=='checked=true') ? "": "AND status='O'";
}
else
{
//Sets up the session for later use or enter
$checked = "";
$status = "AND status='O'";
$_SESSION['ShowMore'] = "";
}
//SQL code
$sql = "SELECT * FROM listings WHERE user_id='".$_SESSION['username']."' $status ORDER BY listings.listing_id DESC";
$result = pg_query(db_connect(), $sql ." LIMIT 200 ");
$records = pg_num_rows($result);
echo "<br/><br/>";
$search = $sql;
if (isset($_GET ['submit']))
{
$button = $_GET ['submit'];
$search = $sql;
}
$search_exploded = explode (" ", $search);
$x = "";
$construct = $sql;
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="title LIKE '%$search_each%'";
else
$construct .="AND title LIKE '%$search_each%'";
}
//USED TO MAKE THE NUMBER OF PAGINATE
$constructs = $sql;/*"SELECT * FROM listings
WHERE 1 = 1 AND (listings.city = 4 OR listings.city = 8 OR listings.city = 64)
AND (listings.bedrooms = 16 OR listings.bedrooms = 32)
AND (listings.property_type = 2 OR listings.property_type = 8 OR listings.property_type = 128)
AND listings.price >= 125000 AND listings.price <= 900000
AND listings.status = 'O' ORDER BY listings.listing_id";*/
//echo $constructs;
$run = pg_query(db_connect(),$constructs);
$foundnum = pg_num_rows($run);
//Shows the number of results match the criteria
echo "<h2 align=\"center\">Show current listings </h2>";
//echo "<p>$foundnum results found !<p>";
//sets the number of houses per pages
$per_page = PAGE_LIMIT;
$start = isset($_GET['start']) ? $_GET['start']: 0;
//find the appropriate number of pages needed to display the page
$max_pages = ceil($foundnum / $per_page);
//Page starts at the first records
if(!$start)
$start=0;
//Set up the query
$getquery = pg_query(db_connect(), $sql. " LIMIT $per_page OFFSET $start");
//echo $_SESSION['Where']. " ORDER BY listings.listing_id DESC LIMIT $per_page OFFSET $start <br>";
//_______________________________________________________________________________________________________CREATES THE TABLE
echo "\n<table border=\"0\">";
$i=0;
while($runrows = pg_fetch_assoc($getquery))
{
$listing_id = $runrows['listing_id'];
$user_id = $runrows['user_id'];
$city = $runrows['city'];
$headline = $runrows['headline'];
$description = $runrows['description'];
$bed = $runrows['bedrooms'];
$bath = $runrows['bathrooms'];
$price = $runrows['price'];
$property = $runrows['property_type'];
$garage = $runrows['garage'];
$schools = $runrows['schools'];
$image = $runrows['images'];
if ($i == 0)
{
echo "<tr><th>Listing ID</th><th>Headline</th><th>Edit</th></tr>";
}
$i +=1;
echo "\n<tr><td> ";
echo "$listing_id";
echo "\n</td>";
echo "\n<td align=\"left\">";
echo "<br/><b><a class=\"homelist\" href=\"listing-view.php?submit=Search+source+code&listing_id=$listing_id\" >$headline </a></b> ";
echo "\n</td> \n\t\t<td> <a href=\"listing-update.php?submit=Search+source+code&listing_id=$listing_id\" >EDIT </a> </td> </tr>";
echo "\n<tr><td colspan=\"3\">";
echo "\n\t<hr/>";
echo "\n</td></tr>";
}
echo "\n</table>";
//Pagination Starts
echo "<center>";
$prev = $start - $per_page;
$next = $start + $per_page;
$adjacents = 3;
$last = $max_pages - 1;
if($max_pages > 1)
{
//previous button
if (!($start<=0))
echo " <a href='dashboard.php?submit=Search+source+code&start=$prev'>Prev</a> ";
//In the first 6 pages, it doesn't skip
if ($max_pages < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
$i = 0;
for ($counter = 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='dashboard.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='dashboard.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
elseif($max_pages > 5 + ($adjacents * 2)) //enough pages to hide some but the first two and the next 3 pages
{
//close to beginning; only hide later pages
if(($start/$per_page) < 1 + ($adjacents * 2))
{
$i = 0;
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($i == $start){
echo " <a href='dashboard.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='dashboard.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//in middle; hide some front and some back
elseif($max_pages - ($adjacents * 2) > ($start / $per_page) && ($start / $per_page) > ($adjacents * 2))
{
echo " <a href='dashboard.php?submit=Search+source+code&start=0'>1</a> ";
echo " <a href='dashboard.php?submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start/$per_page)+1; $counter < ($start / $per_page) + $adjacents + 2; $counter++)
{
if ($i == $start){
echo " <a href='dashboard.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='dashboard.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
//close to end; only hide early pages
else
{
echo " <a href='dashboard.php?submit=Search+source+code&start=0'>1</a> ";
echo " <a href='dashboard.php?submit=Search+source+code&start=$per_page'>2</a> .... ";
$i = $start;
for ($counter = ($start / $per_page) + 1; $counter <= $max_pages; $counter++)
{
if ($i == $start){
echo " <a href='dashboard.php?submit=Search+source+code&start=$i'><b>$counter</b></a> ";
}
else {
echo " <a href='dashboard.php?submit=Search+source+code&start=$i'>$counter</a> ";
}
$i = $i + $per_page;
}
}
}
//next button
if (!($start >=$foundnum-$per_page))
echo " <a href='dashboard.php?submit=Search+source+code&start=$next'>Next</a> ";
}
echo "</center>";
echo "</form>";
echo "</div>
</div>
</section>";
}
else
{
header("Location: /");
}
?>
<?php include 'footer.php'; ?>
<file_sep><?php
/*
Group 13
September 29, 2016
WEBD3201
The main page
*/
$title = "Home Page";
$date = "September 29, 2016";
$filename = "index.php";
$description = "Home Page for realtor";
include("header.php");
?>
<div id="index">
<!-- start of main page content. -->
<br/><br/>
<h1>Welcome to Houses Connected®</h1>
<hr/>
<h1>Your real estate needs ends here!</h1>
<p>
Tired of searching through the newspapers for real estate? Tried using other servies and had bad experiences?<br/>
Houses Connected makes searching easier and faster.<br/> By having listers post their ad of their home, users can easily search
through with many filters.
</p>
<br/>
<table>
<tr>
<td><img src="./Houses/ajax.jpg" class="imagesize1" alt="Ajax House" /></td>
<td><img src="./Houses/pickering.JPG" class="imagesize1" alt="Pickering House"/></td>
<td><img src="./Houses/brampton_house.jpg" class="imagesize1" alt="Brampton House"/></td>
</tr>
</table>
<br/>
<h3>To start searching for your new home, click <a href="./listing-cities.php">HERE</a> or click "Search" on the top of the page.</h3>
<h3>Returning user? Click <a href="./login.php">HERE</a> or click "Login" or "Register" if you're a new user.</h3>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<!-- end of main page content -->
</div>
<?php include 'footer.php'; ?>
|
0c3ac6dfb5c5aaac97608fbfec83857f749b5dd6
|
[
"Markdown",
"SQL",
"PHP"
] | 59
|
PHP
|
amaraladil/Realtor-Website
|
2be34b3cf0df94e515bc5e49771d0b6dbab9a85f
|
18db47ce620e53936a7e94a7b045c78c7554f18a
|
refs/heads/master
|
<file_sep>###############################################################
#
# 权限鉴定
#
#
#
###############################################################
import json
import logging
import fcutils
import pymysql
_log = logging.getLogger()
# 配置文件地址
_CONF_HOST = 'https://1837732264572668.cn-shanghai.fc.aliyuncs.com/2016-08-15/proxy/ly-config/getConfigByName/'
def isLogin(environ):
''' 验证是否已登录,登录则更新token
:return 错误返回 False
:return 成功返回 True
'''
oldPayload = getTokenFromHeader(environ)
if oldPayload == None:
return False
return True
def getTokenFromHeader(environ):
''' 验证是否存在3RDSession,存在返回解码的值失败返回None
'''
# 验证头信息
if 'HTTP_3RD_SESSION' not in environ:
return None
http3RdSession = environ['HTTP_3RD_SESSION'].replace('\\n', '\n')
return decode(http3RdSession)
def getDB():
# 获取数据库连接配置
conf = json.loads(fcutils.getDataForStr(_CONF_HOST, 'ly_common_sql.json').text)
db_conf = json.loads(conf['data'])
# 连接数据库
db = pymysql.connect(db_conf['url'], db_conf['username'], db_conf['password'], db_conf['database'], charset="utf8", cursorclass=pymysql.cursors.DictCursor)
return db
def decode(data):
''' jwt解锁
'''
pub_key = json.loads(fcutils.getDataForStr(_CONF_HOST, 'rsa_public_key.pem').text)['data']
request_data = fcutils.decode(data, pub_key)
return request_data
def updateToken(payload):
''' 更新token
'''
# 一个月
if payload['keep'] == 1:
exp = fcutils.timeLater(1, 'month')
payload['exp'] = exp
return payload
else:
exp = fcutils.timeLater(0.5, 'hour')
payload['exp'] = exp
return payload
def authRight(environ):
''' 权限验证,成功返回True,失败返回False
'''
db = getDB()
cursor = db.cursor()
# seller_user, sellerId, roles, keep
token = getTokenFromHeader(environ)
if token == None or 'roles' not in token:
return False
# 获取接口地址
requestUri = environ['fc.request_uri']
fcInterfaceURL = requestUri.split('proxy')[1].replace('.LATEST', '')
if '?' in fcInterfaceURL:
index = fcInterfaceURL.rfind('?')
fcInterfaceURL = fcInterfaceURL[:index]
roles = ','.join(str(r['id']) for r in token['roles'])
# 获取该用户所有角色支持的接口集合
sql = '''SELECT interface FROM ly_auth_interface WHERE id IN (
SELECT interface_id FROM ly_auth_access_interface WHERE access_id IN (
SELECT access_id FROM ly_auth_role_access WHERE role_id IN (%s))) AND `delete`="0"''' % roles
cursor.execute(sql)
roleUrls = cursor.fetchall()
if roleUrls == None:
return False
cursor.close()
interfaces = [rurl['interface'] for rurl in roleUrls]
return fcInterfaceURL in interfaces
def getBodyAsJson(environ):
''' 获取json格式的请求体
'''
try:
request_body_size = int(environ.get('CONTENT_LENGTH', 0))
except (ValueError):
request_body_size = 0
return json.loads(environ['wsgi.input'].read(request_body_size))
def getBodyAsStr(environ):
''' 获取string格式的请求体
'''
try:
request_body_size = int(environ.get('CONTENT_LENGTH', 0))
except (ValueError):
request_body_size = 0
return environ['wsgi.input'].read(request_body_size)
def encodeToken(data):
''' 加密token
格式:header.payload.signature
:param data 签名参数
:return 成功返回加密值,失败返回None
'''
conf = json.loads(fcutils.getDataForStr(_CONF_HOST, 'rsa_private_key.pem').text)
if conf['status'] != '200':
# 出错处理
return None
priv_key = conf['data']
token_value = fcutils.encode(data, priv_key)
return token_value
<file_sep>import fcutils
def getShanghaiOss(bucketName):
return fcutils.ShanghaiOSS('LTAI4QwuEHvGYNd1', '<KEY>', bucketName)<file_sep>__version__ = '0.2.2'
from .right import (
isLogin, getTokenFromHeader, getDB, decode, updateToken, authRight, getBodyAsJson, getBodyAsStr, encodeToken
)
from .oss import (
getShanghaiOss
)
|
3c65e6b13982de8f96415f539261217736197f00
|
[
"Python"
] | 3
|
Python
|
l616769490/mengyou
|
66b3bfe1816c772e85ed6f69976a26089119847c
|
b600b987de7256e825786c23b71d343f1b18ec2d
|
refs/heads/main
|
<repo_name>GonzaloRamos/Todo-list<file_sep>/JS/main.js
//Variables con la imagen SVG
let removeSVG =
'<svg class="fill" aria-hidden="true" data-prefix="fal" data-icon="trash-alt" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" class="fill" ><path fill="currentColor" d="M336 64l-33.6-44.8C293.3 7.1 279.1 0 264 0h-80c-15.1 0-29.3 7.1-38.4 19.2L112 64H24C10.7 64 0 74.7 0 88v2c0 3.3 2.7 6 6 6h26v368c0 26.5 21.5 48 48 48h288c26.5 0 48-21.5 48-48V96h26c3.3 0 6-2.7 6-6v-2c0-13.3-10.7-24-24-24h-88zM184 32h80c5 0 9.8 2.4 12.8 6.4L296 64H152l19.2-25.6c3-4 7.8-6.4 12.8-6.4zm200 432c0 8.8-7.2 16-16 16H80c-8.8 0-16-7.2-16-16V96h320v368zm-176-44V156c0-6.6 5.4-12 12-12h8c6.6 0 12 5.4 12 12v264c0 6.6-5.4 12-12 12h-8c-6.6 0-12-5.4-12-12zm-80 0V156c0-6.6 5.4-12 12-12h8c6.6 0 12 5.4 12 12v264c0 6.6-5.4 12-12 12h-8c-6.6 0-12-5.4-12-12zm160 0V156c0-6.6 5.4-12 12-12h8c6.6 0 12 5.4 12 12v264c0 6.6-5.4 12-12 12h-8c-6.6 0-12-5.4-12-12z" class="fill"></path></svg>';
let completeSVG =
'<svg aria-hidden="true" data-prefix="fal" data-icon="check-circle" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" class="svg-inline--fa fa-check-circle fa-w-16 fa-7x fill"><path fill="currentColor" d="M256 8C119.033 8 8 119.033 8 256s111.033 248 248 248 248-111.033 248-248S392.967 8 256 8zm0 464c-118.664 0-216-96.055-216-216 0-118.663 96.055-216 216-216 118.664 0 216 96.055 216 216 0 118.663-96.055 216-216 216zm141.63-274.961L217.15 376.071c-4.705 4.667-12.303 4.637-16.97-.068l-85.878-86.572c-4.667-4.705-4.637-12.303.068-16.97l8.52-8.451c4.705-4.667 12.303-4.637 16.97.068l68.976 69.533 163.441-162.13c4.705-4.667 12.303-4.637 16.97.068l8.451 8.52c4.668 4.705 4.637 12.303-.068 16.97z" class="fill"></path></svg>';
let buttonAdd = document.getElementById("add");
let textField = document.getElementById("item");
let data = (localStorage.getItem("listaTodo")) ? JSON.parse(localStorage.getItem("listaTodo")):{
todo: [],
complete: [],
};
renderTodoList()
console.log(data);
function renderTodoList () {
if(!data.todo.length && !data.complete.length) return;
for (let i=0; i < data.todo.length; i++) {
let value = data.todo[i]
addItemTodo(value)
}
for (let j = 0; j< data.complete.length; j++) {
let value = data.complete[j];
addItemTodo(value, true);
}
}
//Usuario clickea en el botton de agregado
//Solo si hay texto en el campo de todo list
buttonAdd.addEventListener("click", function () {
let value = document.getElementById("item").value;
if (value) {
addItem(value)
}
});
textField.addEventListener("keypress", function (e) {
let value = document.getElementById("item").value;
if (e.key === "Enter" && value) {
addItem(value)
}
});
function dataObjectUpdate (){
localStorage.setItem("listaTodo", JSON.stringify(data))
}
function addItem (value) {
addItemTodo(value);
document.getElementById("item").value = "";
data.todo.push(value);
dataObjectUpdate();
}
function removeItem() {
let item = this.parentNode.parentNode;
let parent = item.parentNode;
let id = parent.id;
let value = parent.innerText;
if (id === "todo") {
data.todo.splice(data.todo.indexOf(value), 1);
} else {
data.complete.splice(data.complete.indexOf(value), 1);
}
dataObjectUpdate ()
parent.removeChild(item);
}
function completeItem() {
let item = this.parentNode.parentNode;
let parent = item.parentNode;
let id = parent.id;
let value = item.innerText;
//Cambia del array TODO al Complete
if (id === "todo") {
data.todo.splice(data.todo.indexOf(value), 1);
data.complete.push(value);
} else {
data.complete.splice(data.complete.indexOf(value), 1);
data.todo.push(value);
}
//Revisa si el item deberia ser agregado a la lista de por hacer o ya esta echo. Puede volver a ir a la lista de volver a hacer
let target =
id === "todo"
? document.getElementById("complete")
: document.getElementById("todo");
dataObjectUpdate ()
parent.removeChild(item);
target.insertBefore(item, target.childNodes[0]);
}
//Funcion que agrega al HTML
function addItemTodo(item, completed) {
let list = (completed) ? document.getElementById("complete"):document.getElementById("todo");
let todo = document.createElement("li");
todo.innerText = item;
let buttons = document.createElement("div");
buttons.classList.add("buttons");
let remove = document.createElement("button");
remove.classList.add("remove");
remove.innerHTML = removeSVG;
//Agregar evento de click para borrar elemento de la lista
remove.addEventListener("click", removeItem);
let complete = document.createElement("button");
complete.classList.add("complete");
complete.innerHTML = completeSVG;
//Agregar click event para cuando completas
complete.addEventListener("click", completeItem);
buttons.appendChild(remove);
buttons.appendChild(complete);
todo.appendChild(buttons);
list.insertBefore(todo, list.childNodes[0]);
dataObjectUpdate ()
}
|
6352e1b82f9b27d25082046e882e36bde2d6d517
|
[
"JavaScript"
] | 1
|
JavaScript
|
GonzaloRamos/Todo-list
|
31847c9d17dbf63614653b9e8ec1ede0fe0b3754
|
9e7cfa4d191c92216bab800ec33382d3652d4dbb
|
refs/heads/master
|
<file_sep>const level_character = document.getElementById('level') ;
const melee_skill_character = document.getElementById('melee_skill');
const weapon_attack_character = document.getElementById('weapon_atk');
const melee_ring_item = document.getElementById('melee_ring');
const shield_item = document.getElementById('shield');
const melee_sword0_item = document.getElementById('melee_sword0');
const melee_sword1_item = document.getElementById('melee_sword1');
const melee_sword3_item = document.getElementById('melee_sword3');
const submit = document.getElementById('submit');
const best_hit = document.getElementById('best_hit');
const inputs = document.querySelectorAll('.items');
const addskill = document.getElementById('add_skill')
const medium_hit = document.getElementById('medium_hit')
const min_hit = document.getElementById('min_hit')
var radioValues = [];
level = 0.6;
melee_skill = 1.4;
weapon_attack = 2.2;
function addition (a, b, c) { //dodawanie
return a + b + c;
}
function score_hit(value, decimal) {
let o1 = Number(level_character.value);
let o2 = Number(melee_skill_character.value);
let o3 = Number(weapon_attack_character.value);
let o4 = Number(addskill.innerHTML);
if (o1 <= 0 || o2 <= 0 || o3 <= 0) {
alert ("Wprowadź wartość");
}else {
score = ((o1 * level) + ((o2 + o4) * melee_skill) + (o3 * weapon_attack) * 2.5);
window.document.getElementById("best_hit").innerHTML = score.toFixed(1);
score = ((o1 * level) + ((o2 + o4) * melee_skill) + (o3 * weapon_attack) * 1.2);
window.document.getElementById("medium_hit").innerHTML = score.toFixed(1);
score = ((o1 * level) + ((o2 + o4) * melee_skill) + (o3 * weapon_attack) * 0.2);
window.document.getElementById("min_hit").innerHTML = score.toFixed(1);
}
}
inputs.forEach(input => {
input.addEventListener('change', e => {
const element = e.target;
console.log()
if (element.checked) {
if((element.id).includes("melee_sword")) {
if(radioValues.length > 0) {
addskill.textContent = Number(addskill.textContent) - Number(radioValues[0].value);
}
radioValues = [{
id: element.id,
value: element.value
}]
addskill.textContent = Number(addskill.textContent) + Number(element.value);
}else{
if(element.id == "melee_ring") {
console.log(`dodam: ${element.value}`)
}
addskill.textContent = Number(addskill.textContent) + Number(element.value);
}
} else {
if(element.id == "melee_ring") {
console.log(`odejme: ${element.value}`)
}
addskill.textContent = Number(addskill.textContent) - Number(element.value);
}
});
})<file_sep>function Instagram() {
return (
<>
<section>
<div className="main">
<div className="container">
<div className="bgc">
<img src="img/phone.png" alt="" />
<div className="bgc-windows">
<img src="img/window.jpg" alt="" />
</div>
</div>
<div className="account">
<div className="cont1">
<img
className="imginstagram"
src="img/instagram_text.png"
alt=""
/>
<input
type="text"
name=""
id=""
placeholder="Numer telefonu, nazwa użytkownika lub adr..."
/>
<input type="password" name="" id="" placeholder="Hasło" />
<a className="login-btn" href="">
<p> Zaloguj się</p>
</a>
<div className="margin-className">
<div className="margin-left"></div>
</div>
<p>LUB</p>
<div className="margin-right"></div>
</div>
<div className="login-fb">
<div className="login-fb-position">
<img className="fb-icon" src="img/fb.png" alt="" />
<a href="">Zaloguj się przez Facebooka</a>
</div>
<div className="log-pass">
<a href="">Nie pamiętasz hasła?</a>
</div>
</div>
<div className="cont2">
<div className="cont2-style">
<p>Nie masz konto?</p>
<a href="">Zarejestruj się</a>
</div>
</div>
<div className="cont3">
<p>Pobierz aplikacje</p>
<div className="icons">
<img src="img/appstore.png" alt="" />
<img src="img/googleplay.png" alt="" />
</div>
</div>
</div>
</div>
</div>
</section>
<footer>
<nav>
<a href="">INFORMACJA</a>
<a href="">POMOC</a>
<a href="">PRASA</a>
<a href="">API</a>
<a href="">PRACA</a>
<a href="">PRYWATNOŚĆ</a>
<a href="">REGULAMIN</a>
<a href="">LOKALIZACJE</a>
<a href="">NAJPOPULARNIEJSZE KONTA</a>
<a href="">HASZTAGI</a>
<a href="">JĘZYK</a>
<p>© 2020 INSTAGRAM FACEBOOKA</p>
</nav>
</footer>
</>
);
}
export default Instagram;
<file_sep># my-projects
https://lukaszprotosawicki.github.io/my-projects/
Here i have my projects!
<file_sep>
const btnStart = document.getElementById('start')
const btnNext = document.getElementById('next')
const btnStop = document.getElementById('stop')
const btnPause = document.getElementById('pause')
const btnSave = document.getElementById('save')
const btnReset = document.getElementById('reset')
const panelTime = document.getElementById('time')
const panelScores = document.getElementById('scores')
const closePopup = document.getElementById('close_popup');
const popup = document.getElementById('popup');
const oldScores = document.getElementById('oldscores');
let time = 0;
btnNext.disabled = true;
let idI;
let pauseStatus = false;
let data = [];
// const fetchData = () => {
// firebase.firestore().collection('data').onSnapshot((data) => getDataFromFirebase(data));
// }
window.onload = function () {
getDataFromFirebase();
}
const getDataFromFirebase = () => {
// const dataTimes = firebase.database().ref('data').limitToLast(1);
oldScores.innerHTML = "";
db.collection('data').get().then((snapshot) => {
snapshot.docs.forEach(doc => {
console.log(doc.data())
let dataTime = doc.data()
let scoresItem = (dataTime.times).join('<br>');
let score = document.createElement('div');
score.className = "score";
score.innerHTML = `<div class="title">${dataTime.title}</div><div class="times">${scoresItem}</div>`;
oldScores.appendChild(score);
})
})
}
const start = () => {
if (btnStart.style.display === "block") {
btnStart.style.display = "none";
btnStop.style.display = "block";
btnSave.style.display = "none";
idI = setInterval(startTime, 10);
btnNext.disabled = false;
pauseStatus = false;
} else {
btnStart.style.display = "none";
btnStop.style.display = "block";
idI = setInterval(startTime, 10);
btnNext.disabled = false;
}
}
const startTime = () => {
time++
panelTime.textContent = (time / 100).toFixed(2).replace('.', ':');
}
const stopp = () => {
if (btnStop.style.display === "block") {
btnStop.style.display = "none";
btnStart.style.display = "block";
btnSave.style.display = "block";
clearInterval(idI);
btnNext.disabled = true;
} else {
btnStop.style.display = "none";
btnStart.style.display = "block";
}
}
const reset = () => {
time = 0;
panelTime.textContent = "0:00"
clearInterval(idI);
btnStop.style.display = "none";
btnStart.style.display = "block";
document.getElementById('scores').innerHTML = "";
}
const pause = () => {
if (btnStart.style.display === "none") {
clearInterval(idI);
btnStart.style.display = "block";
btnStop.style.display = "none";
// btnNext.disabled = true;
pauseStatus = true;
btnSave.style.display = "block";
} else {
idI = setInterval(startTime, 10);
btnStart.style.display = "none";
btnStop.style.display = "block";
btnNext.disabled = false;
pauseStatus = false;
btnSave.style.display = "none";
}
}
const next = () => {
if (pauseStatus === false) {
let tableScores = document.getElementById("scores");
let newPlayer = document.createElement("div");
let names = ['Lukasz', 'Angelika', 'Justyna', 'Kamil', 'Grzesiek', 'Dawid', 'Agnieszka', 'Pawel', 'Dominik', 'Beata', 'Renata', 'Karolina', 'Judit', 'Ewa', 'Klaudia', 'Monika', 'Oskar', 'Bartek', 'Helena', 'Anna', 'Emanuela', 'Jessica', 'Brajanek', 'Cesar', 'Julian'];
let randomNames = "";
// console.log(pauseStatus)
randomNames = names[Math.floor(Math.random() * names.length)];
// newPlayer.innerHTML = (time / 100).toFixed(2) + " " + randomNames;
newPlayer.innerHTML = ((time / 100).toFixed(2)).replace('.', ':') + " " + randomNames;
tableScores.appendChild(newPlayer);
data = [...data, ((time / 100).toFixed(2)).replace('.', ':')]
} else {
pauseStatus = true;
alert("Zapauzowałeś stoper, nie możesz zapisać rekordu")
}
}
const close = () => {
popup.classList.remove('active');
let postName = document.getElementById('post_name').value;
const newData = {
times: data,
title: postName
};
firebase.firestore().collection('data').add(newData);
postName.value = "";
data = [];
reset();
getDataFromFirebase();
}
btnStart.addEventListener('click', start);
btnNext.addEventListener('click', next);
btnStop.addEventListener('click', stopp);
btnPause.addEventListener('click', pause);
btnSave.addEventListener('click', function () {
popup.classList.add('active');
});
btnReset.addEventListener('click', reset);
closePopup.addEventListener('click', close)
// let inputKey = document.getElementById("scores");
// let inputValue = document.getElementById("scores");
// let btnSave1 = document.getElementById("save");
// reloadData();
// btnSave1.addEventListener("click", event => {
// let key = inputKey;
// let value = inputValue;
// localStorage.setItem(key, value);
// })<file_sep>import GalleryGrid from "./components/gallery-grid/GalleryGrid";
import Instagram from "./components/instagram/Instagram";
function App() {
return (
<div className="app">
<GalleryGrid />
<Instagram />
</div>
);
}
export default App;
<file_sep>function GalleryGrid() {
return (
<div className="gallery-grid">
<img className="pic1" src="img/flamenco.jpg" alt="" />
<img className="pic2" src="img/flaming.jpg" alt="" />
<img className="pic3" src="img/glebia.jpg" alt="" />
<img className="pic4" src="img/jasno.jpg" alt="" />
<img className="pic5" src="img/kobieta.jpg" alt="" />
<img className="pic6" src="img/zachod.jpg" alt="" />
</div>
);
}
export default GalleryGrid;
<file_sep>import "./App.css";
import React, { Component } from "react";
class App extends Component {
state = {
text: "w tym roku",
error: "",
};
handleDateChange = (e) => {
// console.log("zmiana");
const value = this.refs.number.value;
console.log(value);
};
render() {
return (
<div>
<input onChange={this.handleDateChange} type="text" ref="number" />
<p>Odp: {this.state.text} </p>
</div>
);
}
}
export default App;
|
6f7b2ad816cb5c0c7e3b2f38d6c6b409a65d8341
|
[
"JavaScript",
"Markdown"
] | 7
|
JavaScript
|
lukaszprotosawicki/my-projects
|
25c31076c97f8e8cd02795172cb4f2bdab4a65d3
|
54c1ba1f272024f53ce3d4cd21381301fd0635ed
|
refs/heads/master
|
<repo_name>a815172328169/csv_to_mysql_pro<file_sep>/lanjing_data_process/csv_data_process.py
# -*- coding:utf-8 -*-
import pandas as pd
import time
import yaml
from db_connection import Mysql
with open('config.yaml', 'r', encoding='utf8') as f:
str_conf = f.read()
config = yaml.load(str_conf, Loader=yaml.FullLoader)
class DataToMysql():
def get_data(self, file_name):
# 用pandas读取csv
data = pd.read_csv(file_name)
data_list = []
for name, a, available, bk_cloud_id, charset, content_length, error_code, media_type, message, method, \
node_id, response_code, status, steps, task_duration, task_id, task_type, url in zip(
data['name'], data['time'], data['available'], data['bk_cloud_id'], data['charset'], data['content_length'],
data['error_code'],
data['media_type'], data['message'], data['method'], data['node_id'], data['response_code'], data['status'],
data['steps'], data['task_duration'],
data['task_id'], data['task_type'], data['url']):
str_time = time.localtime(float(str(a)[:-9]))
c_time = time.strftime('%Y-%m-%d %H:%M:%S', str_time)
data_list.append([name, c_time, available, bk_cloud_id, charset, content_length, error_code, media_type,
message, method, node_id, response_code, status, steps, task_duration, task_id, task_type,
url])
return data_list
def data_to_mysql(self, data_list):
mysql = Mysql(
host=config['HOST'],
user=config['USER'],
password=config['<PASSWORD>'],
database=config['DATABASE']
)
success_data = len(data_list)
fail_data = 0
i = 1
# 数据写入数据库
for dataList in data_list:
sql = "INSERT INTO uptimecheck_http_2(name, time, available, bk_cloud_id, charset, content_length, error_code, media_type, message, method, " \
"node_id, response_code, status, steps, task_duration, task_id, task_type, url) VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'," \
"'%s','%s','%s','%s','%s','%s','%s','%s')" % (
dataList[0],
dataList[1],
dataList[2],
dataList[3],
dataList[4],
dataList[5],
dataList[6],
dataList[7],
dataList[8],
dataList[9],
dataList[10],
dataList[11],
dataList[12],
dataList[13],
dataList[14],
dataList[15],
dataList[16],
dataList[17],
)
res = mysql.add_data(sql)
if not res:
success_data -= 1
fail_data += 1
print('第{}条数据录入失败'.format(i))
i += 1
print('成功录入{}条数据,失败{}条'.format(success_data, fail_data))
<file_sep>/lanjing_data_process/db_connection.py
import pymysql
class Mysql:
def __init__(self, host, user, password, database):
try:
self.conn = pymysql.connect(host=host, user=user, password=<PASSWORD>, database=database) # 连接数据库
except Exception as e:
print(e, '数据库连接失败')
else:
print('数据库连接成功')
self.cur = self.conn.cursor()
'''创建表'''
def create_table(self, sql):
try:
self.cur.execute(sql)
except Exception as e:
print(e, '表创建失败')
else:
print('表创建成功')
'''添加数据'''
def add_data(self, sql):
res = self.cur.execute(sql)
if res:
self.conn.commit()
return True
else:
self.conn.rollback()
return False
<file_sep>/lanjing_data_process/main.py
import os
from csv_data_process import DataToMysql
import yaml
if __name__ == '__main__':
with open('config.yaml', 'r', encoding='utf8') as f:
str_conf = f.read()
config = yaml.load(str_conf, Loader=yaml.FullLoader)
file_name_list = os.listdir(config['FILEDIR'])
task = DataToMysql()
# # 批量录入文件夹中所有文件
# i = 1
# for file_name in file_name_list:
# print('{}开始录入'.format(file_name))
# data_list = task.get_data(config['FILEDIR']+file_name)
# task.data_to_mysql(data_list)
# print('{}录入完成'.format(file_name))
# if i == len(file_name_list):
# print('数据全部录入完毕')
# i += 1
# time.sleep(5)
# # 录入当天数据
# cur_date = time.strftime('%Y%m%d')
# data_list = task.get_data(config['FILEDIR'] + 'influxbak' + cur_date + '.csv')
# task.data_to_mysql(data_list)
# 录入指定文件数据
file_path = 'C:/Users/ISSUSER/Desktop/data/influxbak20210915.csv'
data_list = task.get_data(file_path)
task.data_to_mysql(data_list)
|
ce84553203f9764380a64acf53a073d6c04a048a
|
[
"Python"
] | 3
|
Python
|
a815172328169/csv_to_mysql_pro
|
3c6fa85878a19f28fdd20fa7e0575cbdc33ab387
|
6fb38b84120cd308d8ff111960a12eb9c6a2acae
|
refs/heads/master
|
<file_sep># javascript-calculator
This project is part of FCC curriculum. More info: https://www.freecodecamp.com/challenges/build-a-javascript-calculator
A Pen created at CodePen.io. You can find this one at http://codepen.io/NadaSadek/pen/RGYXWQ.
<file_sep> $(document).ready(function(){
var finalRes = "";
var num = "";
var check = -1;
$(".btn").click(function() {
if($("#res2").text() == "Digit Limit Met!")
$("#res2").html("");
$('#res1').css('font-size', '15px');
if($('#res1').text().length > 17 || $('#res2').text().length > 21){
num = "";
finalRes = "";
$('#res1').html(0);
$('#res2').html("Digit Limit Met!");
}
});
$( "#dot" ).click(function() {
if(check == 1 && finalRes == ""){
check = -1;
num="";
}
if(num === "" || finalRes === "" || operatorChecker(finalRes.slice(-1))){
num = "0.";
}
else if(!(num.includes(".")))
num += ".";
$("#res1").html(num);
});
$( "#c" ).click(function() {
finalRes = "";
num = "";
$("#res2").html(finalRes);
$("#res1").html(num);
});
$( "#ce" ).click(function() {
num = "";
$("#res1").html(0);
});
$( "#multi" ).click(function() {
if(num.charAt(num.length-1) === ".")
num = num.substr(0, num.length - 1);
finalRes += num;
num = "";
if(finalRes != ""){
finalRes = replaceOperator(finalRes);
finalRes += "*";
$("#res2").html(finalRes);
$("#res1").html("");
}
});
$( "#minus" ).click(function() {
finalRes += num;
num = "";
if(finalRes != ""){
finalRes = replaceOperator(finalRes,"-");
finalRes += "-";
$("#res2").html(finalRes);
$("#res1").html("");
}
});
$( "#plus" ).click(function() {
finalRes += num;
num = "";
if(finalRes != ""){
finalRes = replaceOperator(finalRes);
finalRes += "+";
$("#res2").html(finalRes);
$("#res1").html("");
}
});
$( "#divide" ).click(function() {
finalRes += num;
num = "";
if(finalRes != ""){
finalRes = replaceOperator(finalRes);
finalRes += "/";
$("#res2").html(finalRes);
$("#res1").html("");
}
});
$( "#one" ).click(function() {
if(check == 1 && finalRes == ""){
check = -1;
num="";
}
num += "1";
$("#res1").html(num);
});
$( "#two" ).click(function() {
if(check == 1 && finalRes == ""){
check = -1;
num="";
}
num += "2";
$("#res1").html(num);
});
$( "#three" ).click(function() {
if(check == 1 && finalRes == ""){
check = -1;
num="";
}
num += "3";
$("#res1").html(num);
});
$( "#four" ).click(function() {
if(check == 1 && finalRes == ""){
check = -1;
num="";
}
num += "4";
$("#res1").html(num);
});
$( "#five" ).click(function() {
if(check == 1 && finalRes == ""){
check = -1;
num="";
}
num += "5";
$("#res1").html(num);
});
$( "#six" ).click(function() {
if(check == 1 && finalRes == ""){
check = -1;
num="";
}
num += "6";
$("#res1").html(num);
});
$( "#seven" ).click(function() {
if(check == 1 && finalRes == ""){
check = -1;
num="";
}
num += "7";
$("#res1").html(num);
});
$( "#eight" ).click(function() {
if(check == 1 && finalRes == ""){
check = -1;
num="";
}
num += "8";
$("#res1").html(num);
});
$( "#nine" ).click(function() {
if(check == 1 && finalRes == ""){
check = -1;
num="";
}
num += "9";
$("#res1").html(num);
});
$( "#zero" ).click(function() {
if(check == 1 && finalRes == ""){
check = -1;
num="";
}
num += "0";
$("#res1").html(num);
});
$( "#eql" ).click(function() {
if(num === "")
finalRes = replaceOperator(finalRes);
if(operatorChecker(finalRes.charAt(0))){
finalRes = finalRes.substr(1);
}
finalRes += num;
finalRes = eval(finalRes);
num = eval(finalRes);
num = num.toString();
$("#res2").html("");
$("#res1").html(finalRes);
var sectionWidth = $("#result").width();
var spanWidth = $("#res1").width();
/* var originalFontSize = 15;
var newFontSize = (sectionWidth/spanWidth) * originalFontSize;*/
/* $("#res1").css("font-size", spanWidth/10); */
finalRes = "";
check = 1;
});
});
function operatorChecker(x){
var arrOp=['*','/','+','-'];
if(arrOp.indexOf(x) != -1)
return true;
else return false;
}
function replaceOperator(str){
if(operatorChecker(str.slice(-1))){
return str.substr(0, str.length - 1);
}
else return str;
}
function findOp(str){
var arrOp=['*','/','+','-'];
for(var i = 0; i < arrOp.length; i++){
if(str.indexOf(i) != -1)
return true;
}
return false;
}
|
e308fb2edfd3e9bf39f258612646f01a1eb4c186
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
NadaSadek/javascript-calculator
|
1617889c8ef226bf01cb09d0aaf8833577227dcc
|
a36280fb3aee30c0e395ffd26d82f7cc152ef102
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
"""
wechatpy.component
~~~~~~~~~~~~~~~
This module provides client library for WeChat Open Platform
:copyright: (c) 2015 by hunter007.
:license: MIT, see LICENSE for more details.
"""
from __future__ import absolute_import, unicode_literals
import time
import json
import six
import requests
from wechatpy._compat import get_querystring
from wechatpy.session.memorystorage import MemoryStorage
from wechatpy.exceptions import WeChatClientException, APILimitedException
from wechatpy.client import WeChatComponentClient
class BaseWeChatComponent(object):
API_BASE_URL = 'https://api.weixin.qq.com/cgi-bin/'
def __init__(self,
component_appid,
component_appsecret,
session=None):
"""
:param component_appid: 第三方平台appid
:param component_appsecret: 第三方平台appsecret
:param component_verify_ticket: 微信后台推送的ticket,此ticket会定时推送
"""
self.component_appid = component_appid
self.component_appsecret = component_appsecret
self.expires_at = None
self.session = session or MemoryStorage()
if isinstance(session, six.string_types):
from shove import Shove
from wechatpy.session.shovestorage import ShoveStorage
querystring = get_querystring(session)
prefix = querystring.get('prefix', ['wechatpy'])[0]
shove = Shove(session)
storage = ShoveStorage(shove, prefix)
self.session = storage
@property
def component_verify_ticket(self):
return self.session.get('component_verify_ticket')
def _request(self, method, url_or_endpoint, **kwargs):
if not url_or_endpoint.startswith(('http://', 'https://')):
api_base_url = kwargs.pop('api_base_url', self.API_BASE_URL)
url = '{base}{endpoint}'.format(
base=api_base_url,
endpoint=url_or_endpoint
)
else:
url = url_or_endpoint
if 'params' not in kwargs:
kwargs['params'] = {}
if isinstance(kwargs['params'], dict) and \
'component_access_token' not in kwargs['params']:
kwargs['params'][
'component_access_token'] = self.access_token
if isinstance(kwargs['data'], dict):
kwargs['data'] = json.dumps(kwargs['data'])
res = requests.request(
method=method,
url=url,
**kwargs
)
try:
res.raise_for_status()
except requests.RequestException as reqe:
raise WeChatClientException(
errcode=None,
errmsg=None,
client=self,
request=reqe.request,
response=reqe.response
)
return self._handle_result(res, method, url, **kwargs)
def _handle_result(self, res, method=None, url=None, **kwargs):
result = res.json()
if 'errcode' in result:
result['errcode'] = int(result['errcode'])
if 'errcode' in result and result['errcode'] != 0:
errcode = result['errcode']
errmsg = result['errmsg']
if errcode == 42001:
# access_token expired, fetch a new one and retry request
self.fetch_component_access_token()
kwargs['params']['component_access_token'] = self.session.get(
'component_access_token'
)
return self._request(
method=method,
url_or_endpoint=url,
**kwargs
)
elif errcode == 45009:
# api freq out of limit
raise APILimitedException(
errcode,
errmsg,
client=self,
request=res.request,
response=res
)
else:
raise WeChatClientException(
errcode,
errmsg,
client=self,
request=res.request,
response=res
)
return result
def fetch_access_token(self):
"""
获取 component_access_token
详情请参考 https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list\
&t=resource/res_list&verify=1&id=open1419<PASSWORD>&token=&lang=zh_CN
:return: 返回的 JSON 数据包
"""
url = '{0}{1}'.format(
self.API_BASE_URL,
'component/api_component_token'
)
return self._fetch_access_token(
url=url,
data=json.dumps({
'component_appid': self.component_appid,
'component_appsecret': self.component_appsecret,
'component_verify_ticket': self.component_verify_ticket
})
)
def _fetch_access_token(self, url, data):
""" The real fetch access token """
res = requests.post(
url=url,
data=data
)
try:
res.raise_for_status()
except requests.RequestException as reqe:
raise WeChatClientException(
errcode=None,
errmsg=None,
client=self,
request=reqe.request,
response=reqe.response
)
result = res.json()
if 'errcode' in result and result['errcode'] != 0:
raise WeChatClientException(
result['errcode'],
result['errmsg'],
client=self,
request=res.request,
response=res
)
expires_in = 7200
if 'expires_in' in result:
expires_in = result['expires_in']
self.session.set(
'component_access_token',
result['component_access_token'],
expires_in
)
self.expires_at = int(time.time()) + expires_in
return result
@property
def access_token(self):
""" WeChat component access token """
access_token = self.session.get('component_access_token')
if access_token:
if not self.expires_at:
# user provided access_token, just return it
return access_token
timestamp = time.time()
if self.expires_at - timestamp > 60:
return access_token
self.fetch_access_token()
return self.session.get('component_access_token')
def get(self, url, **kwargs):
return self._request(
method='get',
url_or_endpoint=url,
**kwargs
)
def post(self, url, **kwargs):
return self._request(
method='post',
url_or_endpoint=url,
**kwargs
)
class WeChatComponent(BaseWeChatComponent):
def create_preauthcode(self):
"""
获取预授权码
"""
return self.post(
'/component/api_create_preauthcode',
data={
'component_appid': self.component_appid
}
)
def query_auth(self, authorization_code):
"""
使用授权码换取公众号的授权信息
:params authorization_code: 授权code,会在授权成功时返回给第三方平台,详见第三方平台授权流程说明
"""
return self.post(
'/component/api_query_auth',
data={
'component_appid': self.component_appid,
'authorization_code': authorization_code
}
)
def refresh_authorizer_token(
self, authorizer_appid, authorizer_refresh_token):
"""
获取(刷新)授权公众号的令牌
:params authorizer_appid: 授权方appid
:params authorizer_refresh_token: 授权方的刷新令牌
"""
return self.post(
'/component/api_authorizer_token',
data={
'component_appid': self.component_appid,
'authorizer_appid': authorizer_appid,
'authorizer_refresh_token': authorizer_refresh_token
}
)
def get_authorizer_info(self, authorizer_appid):
"""
获取授权方的账户信息
:params authorizer_appid: 授权方appid
"""
return self.post(
'/component/api_get_authorizer_info',
data={
'component_appid': self.component_appid,
'authorizer_appid': authorizer_appid,
}
)
def get_authorizer_option(self, authorizer_appid, option_name):
"""
获取授权方的选项设置信息
:params authorizer_appid: 授权公众号appid
:params option_name: 选项名称
"""
return self.post(
'/component/api_get_authorizer_option',
data={
'component_appid': self.component_appid,
'authorizer_appid': authorizer_appid,
'option_name': option_name
}
)
def set_authorizer_option(
self, authorizer_appid, option_name, option_value):
"""
设置授权方的选项信息
:params authorizer_appid: 授权公众号appid
:params option_name: 选项名称
:params option_value: 设置的选项值
"""
return self.post(
'/component/api_set_authorizer_option',
data={
'component_appid': self.component_appid,
'authorizer_appid': authorizer_appid,
'option_name': option_name,
'option_value': option_value
}
)
def get_client_by(self, authorization_code):
"""
通过授权码直接获取 Client 对象
:params authorization_code: 授权code,会在授权成功时返回给第三方平台,详见第三方平台授权流程说明
"""
result = self.query_auth(authorization_code)
access_token = result['authorization_info']['authorizer_access_token']
refresh_token = result['authorization_info']['authorizer_refresh_token'] # NOQA
authorizer_appid = result['authorization_info']['authorizer_appid'] # noqa
return WeChatComponentClient(
authorizer_appid, access_token, refresh_token, self,
session=self.session
)
def get_client(self,
authorizer_appid,
authorizer_refresh_token,
authorizer_access_token=None):
"""
通过 authorizer_appid, access_token, refresh_token获取 Client 对象
:params authorizer_appid: 授权公众号appid
:params authorizer_refresh_token: 刷新令牌
:params authorizer_access_token: 授权方令牌
"""
if not authorizer_access_token:
ret = self.refresh_authorizer_token(
authorizer_appid,
authorizer_refresh_token
)
authorizer_access_token = ret['authorizer_access_token']
authorizer_refresh_token = ret['authorizer_refresh_token']
return WeChatComponentClient(
authorizer_appid,
authorizer_access_token,
authorizer_refresh_token,
self,
session=self.session
)
|
eea3fd58a273d09d428cc666e1569c0dc45f8db9
|
[
"Python"
] | 1
|
Python
|
lunun/wechatpy
|
598db745b0679da00ceedb1284c84b3afa882422
|
c009f9ea16c3598a6402577113ee2e2f09c77fe9
|
refs/heads/master
|
<repo_name>OleksandrNechay/Blog<file_sep>/app/Http/Controllers/Blog/Admin/PostsController.php
<?php
namespace App\Http\Controllers\Blog\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\PostCreateRequest;
use App\Http\Requests\PostUpdateRequest;
use App\Models\Photo;
use App\Models\Post;
use App\Repositories\Blog\PhotoRepository;
use App\Repositories\Blog\PostRepository;
use App\Repositories\Blog\CategoryRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
class PostsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
private $blogPostRepository;
private $blogCategoryRepository;
private $blogPhotoRepository;
public function __construct()
{
$this->blogPhotoRepository = app(PhotoRepository::class);
$this->blogPostRepository = app(PostRepository::class);
$this->blogCategoryRepository = app(CategoryRepository::class);
}
public function mainPage(){
$posts = $this->blogPostRepository->getLastPostsPaginate();
return view('blog.user.main_page', compact('posts'));
}
public function index()
{
$posts = $this->blogPostRepository->getAllWithPaginate();
return view('blog.admin.posts.index', compact('posts'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
*/
public function create()
{
if(Auth::check() && (Auth::user()->role_id == 1)) {
$item = new Post();
$categoryList = $this->blogCategoryRepository->getForComboBox();
return view('blog.admin.posts.edit', compact('item', 'categoryList'));
}else{
return view('blog.access_denied401');
}
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
public function store(PostCreateRequest $request)
{
if(Auth::check() && (Auth::user()->role_id == 1)) {
$data = $request->input();
$user = ['user_id' => Auth::user()->id];
$result = array_merge($user, $data);
$post = (new Post())->create($result);
$file = $request->file('image');
if(isset($file)) {
$img = $request->file('image')->store('images', 'public');
$name = $file->getClientOriginalName();
$url = Str::slug($name);
$image = ['post_id'=> $post->id, 'photos_name' => $name,'photo_url' => $url, 'photo_path' => $img];
$img = (new Photo())->create($image);
}
if ($post) {
return redirect()
->route('blog.admin.posts.edit', [$post->id])
->with(['success' => 'Успішно збережено']);
} else {
return back()
->withErrors(['msg' => 'Помилка зберігання'])
->withInput();
}
}else{
return view('blog.access_denied401');
}
}
/**
* Display the specified resource.
*
* @param \App\Models\Post $post
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$post = $this->blogPostRepository->getEdit($id);
$img = $this->blogPhotoRepository->getImg($id);
return view('blog.user.show_post', compact(['post', 'img']));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Post $post
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
*/
public function edit($id)
{
if(Auth::check() && (Auth::user()->role_id == 1)) {
$item = $this->blogPostRepository->getEdit($id);
if (empty($item)) {
abort(404);
}
$categoryList = $this->blogCategoryRepository->getForComboBox();
return view('blog.admin.posts.edit', compact('item', 'categoryList'));
}else{
return view('blog.access_denied401');
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Post $post
* @return \Illuminate\Http\RedirectResponse
*/
public function update($id, PostUpdateRequest $request)
{
if(Auth::check() && (Auth::user()->role_id == 1)) {
$item = $this->blogPostRepository->getEdit($id);
$data = $request->all();
if (empty($item)) {
return back()
->withErrors(['msg' => "Запис id = [{$id}] не знайдено"])
->withInput();
}
$result = $item->update($data);
if ($result) {
return redirect()
->route('blog.admin.posts.edit', $item->id)
->with(['success' => 'Успішно збережено']);
} else {
return back()
->withErrors(['msg' => 'Помилка зберігання'])
->withInput();
}
}else{
return view('blog.access_denied401');
}
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Post $post
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy($id)
{
if(Auth::check() && (Auth::user()->role_id == 1)) {
$result = Post::destroy($id);
if ($result) {
return redirect()
->route('blog.admin.posts.index')
->with(['success' => "Запис id [$id] успішно видалено"]);
} else {
return back()
->withErrors(['msg' => 'Помилка видалення']);
}
}else{
return view('blog.access_denied401');
}
}
}
<file_sep>/app/Repositories/Blog/CategoryRepository.php
<?php
namespace App\Repositories\Blog;
use App\Models\Category As Model;
use Illuminate\Database\Eloquent\Collection;
class CategoryRepository extends CoreRepository
{
protected function getModelClass(){
return Model::class;
}
public function getEdit($id){
return $this->startConditions()->find($id);
}
public function getForComboBox()
{
//return $this->startConditions()->all();
$columns = implode(',', [
'id',
'CONCAT(id, ". ", title) AS id_title',
]);
/*$result[] = $this->startConditions()->all();
$result[] = $this->startConditions()
->select('blog_categories.*', \DB::raw('id', 'CONCAT(id, " .", title) AS title'))
->toBase()
->get();
*/
$result = $this->startConditions()
->selectRaw($columns)
->toBase()
->get();
return $result;
}
public function getAllWithPaginate($perPage = null)
{
$columns = ['id', 'title', 'parent_id'];
$result = $this->startConditions()
->select($columns)
->with([
'parentCategory:id,title',
])
->paginate($perPage);
return $result;
}
}
<file_sep>/app/Http/Controllers/Blog/Admin/DashboardController.php
<?php
namespace App\Http\Controllers\Blog\Admin;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Repositories\Blog\CategoryRepository;
use App\Repositories\Blog\PostRepository;
use App\Models\Post;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
private $blogPostRepository;
private $blogCategoryRepository;
public function __construct()
{
$this->blogPostRepository = app(PostRepository::class);
$this->blogCategoryRepository = app(CategoryRepository::class);
}
public function dashboard(){
$categories = Category::LastCategories(5);
$posts = Post::LastPosts(5);
return view('blog.admin.Dashboard', compact(['categories', 'posts']));
}
public function categoryPosts(){
$categories = $this->blogCategoryRepository->getAllWithPaginate();
return view('blog.admin.category.categories', compact('categories'));
}
public function getPosts($id){
$posts = $this->blogPostRepository->postCategory($id);
return view('blog.admin.category.category_posts', compact('posts'));
}
public function published(){
$posts = $this->blogPostRepository->isPublished();
return view('blog.admin.posts.published_posts', compact('posts'));
}
public function notPublished()
{
$posts = $this->blogPostRepository->notPublished();
return view('blog.admin.posts.notpublished_posts', compact('posts'));
}
public function deleted(){
$posts = $this->blogPostRepository->deleted();
return view('blog.admin.posts.deleted_posts', compact('posts'));
}
}
<file_sep>/routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Blog\Admin\DashboardController;
use App\Http\Controllers\Blog\Admin\PostsController;
use App\Http\Controllers\Blog\Admin\CategoryController;
use App\Http\Middleware\DashboardMiddleware;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
require __DIR__.'/auth.php';
Route::get('dashboard', [DashboardController::class, 'dashboard'])
->middleware(DashboardMiddleware::class)
->name('dashboard');
Route::get('main', [PostsController::class, 'mainPage'])->name('main');
Route::get('show/{id}',[PostsController::class, 'show'])->name('show');
Route::get('/', function () {
return redirect(route('main'));
});
//Адмінка
$groupData = ['prefix' => 'admin/blog'];
//Category
Route::group($groupData, function() {
$methods = ['index', 'edit' , 'create','store', 'update', ];
Route::resource('categories', CategoryController::class)
->middleware(DashboardMiddleware::class)
->only($methods)
->names('blog.admin.categories');
Route::get('show/categorypost', [DashboardController::class, 'categoryPosts'])
->middleware(DashboardMiddleware::class)->name('categories');
Route::get('show/categoryposts/{id}', [DashboardController::class, 'getPosts'])
->middleware(DashboardMiddleware::class)->name('categoryPosts');
//Posts
Route::resource('posts', PostsController::class)
->middleware(DashboardMiddleware::class)
->except(['show'])
->names('blog.admin.posts');
Route::get('posts/published', [DashboardController::class, 'published'])
->middleware(DashboardMiddleware::class)->name('published');
Route::get('posts/deleted', [DashboardController::class, 'deleted'])
->middleware(DashboardMiddleware::class)->name('deleted');
Route::get('posts/not_published', [DashboardController::class, 'notPublished'])
->middleware(DashboardMiddleware::class)->name('not_published');
});
<file_sep>/app/Repositories/Blog/PostRepository.php
<?php
namespace App\Repositories\Blog;
use App\Models\Post As Model;
class PostRepository extends CoreRepository
{
protected function getModelClass(){
return Model::class;
}
public function getAllWithPaginate()
{
$fields = ['id', 'title', 'slug', 'is_published', 'published_at', 'user_id', 'category_id'];
$result = $this->StartConditions()
->select($fields)
->orderBy('id', 'DESC')
//->with(['category', 'user'])
->with(['category' => function($query){
$query->select(['id', 'title']);
},
'user:id,name'
])
->paginate(25);
return $result;
}
public function getLastPostsPaginate(){
$fields = ['id', 'title', 'slug', 'is_published', 'published_at', 'user_id', 'category_id'];
$result = $this->StartConditions()
->select($fields)
->where('is_published', '1')
->orderBy('created_at', 'DESC')
//->with(['category', 'user'])
->with(['category' => function($query){
$query->select(['id', 'title']);
},
'user:id,name'
])
->paginate(10);
return $result;
}
public function postCategory($id)
{
$fields = ['id', 'title', 'slug', 'is_published', 'published_at', 'user_id', 'category_id'];
$result = $this->StartConditions()
->select($fields)
->where('category_id', '=', $id)
->with(['category' => function ($query) {
$query->select(['id', 'title']);
},
'user:id,name'
])->get();
return $result;
}
public function isPublished()
{
$fields = ['id', 'title', 'slug', 'is_published', 'published_at', 'user_id', 'category_id'];
$result = $this->StartConditions()
->select($fields)
->where('is_published', '1')
->with(['category' => function ($query) {
$query->select(['id', 'title']);
},
'user:id,name'
])->paginate(15);
return $result;
}
public function notPublished()
{
$fields = ['id', 'title', 'slug', 'is_published', 'published_at', 'user_id', 'category_id'];
$result = $this->StartConditions()
->select($fields)
->where('is_published', '0')
->with(['category' => function ($query) {
$query->select(['id', 'title']);
},
'user:id,name'
])->paginate(15);
return $result;
}
public function Deleted()
{
$fields = ['id', 'title', 'slug', 'is_published', 'published_at', 'user_id', 'category_id'];
$result = $this->StartConditions()
->select($fields)
->withTrashed()
->whereNotNull('deleted_at')
->with(['category' => function ($query) {
$query->select(['id', 'title']);
},
'user:id,name'
])->paginate(10);
return $result;
}
public function getEdit($id)
{
return $this->StartConditions()->find($id);
}
}
<file_sep>/app/Models/Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use HasFactory;
use SoftDeletes;
//const UNKNOWN_USER = 1;
protected $fillable = [
'title',
'user_id',
'slug',
'category_id',
'excerpt',
'content_raw',
'is_published',
'published_at',
];
/**
* @var mixed
*/
public function Category(){
return $this->belongsTo(Category::class);
}
public function User(){
return $this->belongsTo(User::class);
}
public function Photos(){
return $this->belongsTo(Photo::class);
}
protected $dates = [
'published_at'
];
public function scopeLastPosts($query, $count){
$posts = $query->orderBy('created_at','DESC')->take($count)->get();
return $posts;
}
}
<file_sep>/app/Http/Controllers/Blog/Admin/CategoryController.php
<?php
namespace App\Http\Controllers\Blog\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\CategoryCreateRequest;
use App\Http\Requests\CategoryUpdateRequest;
use App\Models\Category;
use Illuminate\Http\Request;
use App\Repositories\Blog\CategoryRepository;
use Illuminate\Support\Facades\Auth;
class CategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
private $BlogCategoryRepository;
public function __construct(){
$this->BlogCategoryRepository = app(CategoryRepository::class);
}
public function index()
{
$paginator = $this->BlogCategoryRepository->getAllWithPaginate(10);
return view('blog.admin.category.index', compact('paginator'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
*/
public function create()
{
if(Auth::check() && (Auth::user()->role_id == 1)) {
$item = new Category();
$categoryList = $this->BlogCategoryRepository->getForComboBox();
return view('blog.admin.category.edit', compact('item', 'categoryList'));
}else{
return view('blog.access_denied401');
}
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
public function store(CategoryCreateRequest $request)
{
if(Auth::check() && (Auth::user()->role_id == 1)) {
$data = $request->input();
$item = (new Category())->create($data);
if ($item) {
return redirect()
->route('blog.admin.categories.edit', [$item->id])
->with(['success' => 'Успішно збережено']);
} else {
return back()
->withErrors(['msg' => 'Помилка зберігання'])
->withInput();
}
}else{
return view('blog.access_denied401');
}
}
/**
* Display the specified resource.
*
* @param \App\Models\Category $category
* @return \Illuminate\Http\Response
*/
public function show(Category $category)
{
dd(__METHOD__);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Category $category
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
*/
public function edit($id, CategoryRepository $categoryRepository)
{
if(Auth::check() && (Auth::user()->role_id == 1)) {
$item = $this->BlogCategoryRepository->getEdit($id);
if (empty($item)) {
abort(404);
}
$categoryList = $categoryRepository->getForComboBox();
return view('blog.admin.category.edit', compact('item', 'categoryList'));
}else{
return view('blog.access_denied401');
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Category $category
* @return \Illuminate\Http\RedirectResponse
*/
public function update($id, CategoryUpdateRequest $request)
{
if(Auth::check() && (Auth::user()->role_id == 1)) {
$item = $this->BlogCategoryRepository->getEdit($id);
if (empty($item)) {
return back()
->withErrors(['msg' => "Запис id = [{$id}] не знайдено"])
->withInput();
}
$data = $request->all();
$result = $item->update($data);
if ($result) {
return redirect()
->route('blog.admin.categories.edit', $item->id)
->with(['success' => 'Успішно збережено']);
} else {
return back()
->withErrors(['msg' => 'Помилка зберігання'])
->withInput();
}
}else{
return view('blog.access_denied401');
}
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Category $category
* @return \Illuminate\Http\Response
*/
public function destroy(Category $category)
{
//
}
}
<file_sep>/app/Models/Photo.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
use HasFactory;
protected $fillable = [
'post_id',
'photos_name',
'photo_path',
'photo_url'];
public function Post(){
return $this->hasOne(Post::class);
}
protected $table = 'photos.photos';
}
<file_sep>/app/Observers/PostObserver.php
<?php
namespace App\Observers;
use App\Models\Post;
use Carbon\Carbon;
use Illuminate\Support\Str;
class PostObserver
{
/**
* Handle the blog post "created" event.
*
* @param Post $blogPost
* @return void
*/
// Обробка ПЕРЕД створенням запису
public function creating(Post $blogPost)
{
$this->setPublishedAt($blogPost);
$this->setSlug($blogPost);
$this->setHtml($blogPost);
// $this->setUser($blogPost);
}
public function updating(Post $blogPost)
{
/* $test[] = $blogPost->isDirty();
$test[] = $blogPost->isDirty('is_published');
$test[] = $blogPost->isDirty('user_id');
$test[] = $blogPost->getAttribute('is_published');
$test[] = $blogPost->is_published;
$test[] = $blogPost->getOriginal('is_published');
*/
$this->setPublishedAt($blogPost);
$this->setSlug($blogPost);
}
public function created(Post $blogPost)
{
//
}
/**
* Handle the blog post "updated" event.
*
* @param Post $blogPost
* @return void
*/
public function updated(Post $blogPost)
{
//
}
/**
* Handle the blog post "deleted" event.
*
* @param Post $blogPost
* @return void
*/
public function deleted(Post $blogPost)
{
//
}
/**
* Handle the blog post "restored" event.
*
* @param Post $blogPost
* @return void
*/
public function restored(Post $blogPost)
{
//
}
/**
* Handle the blog post "force deleted" event.
*
* @param Post $blogPost
* @return void
*/
public function forceDeleted(Post $blogPost)
{
//
}
protected function setPublishedAt(Post $blogPost){
if(empty($blogPost->published_at) && $blogPost->is_published){
$blogPost->published_at = Carbon::now();
}
}
protected function setSlug(Post $blogPost){
if(empty($blogPost->slug)){
$blogPost->slug = Str::slug($blogPost->title);
}
}
protected function setHtml(Post $blogPost){
if($blogPost->isDirty('content_raw')){
$blogPost->content_html = $blogPost->content_raw;
}
}
/*
protected function setUser(Post $blogPost){
$blogPost->user_id = auth()->id() ?? Post::UNKNOWN_USER;
}
*/
}
<file_sep>/app/Repositories/Blog/PhotoRepository.php
<?php
namespace App\Repositories\Blog;
use App\Models\Photo As Model;
class PhotoRepository extends CoreRepository
{
protected function getModelClass(){
return Model::class;
}
public function getImg($id)
{
$img = $this->StartConditions()
->select('photo_path')
->where('post_id', $id)
->join('posts', 'posts.id', 'photos.id')
->first();
return $img;
}
}
<file_sep>/app/Observers/CategoryObserver.php
<?php
namespace App\Observers;
use App\Models\Category;
use Illuminate\Support\Str;
class CategoryObserver
{
/**
* Handle the blog category "created" event.
*
* @param Category $blogCategory
* @return void
*/
public function created(Category $blogCategory)
{
//
}
public function creating(Category $blogCategory)
{
$this->setSlug($blogCategory);
}
/**
* Handle the blog category "updated" event.
*
* @param Category $blogCategory
* @return void
*/
public function updated(Category $blogCategory)
{
}
public function updating(Category $blogCategory)
{
$this->setSlug($blogCategory);
}
protected function setSlug(Category $blogCategory){
if(empty($blogCategory->slug)){
$blogCategory->slug = Str::slug($blogCategory->title);
}
}
/**
* Handle the blog category "deleted" event.
*
* @param Category $blogCategory
* @return void
*/
public function deleted(Category $blogCategory)
{
//
}
/**
* Handle the blog category "restored" event.
*
* @param Category $blogCategory
* @return void
*/
public function restored(Category $blogCategory)
{
//
}
/**
* Handle the blog category "force deleted" event.
*
* @param Category $blogCategory
* @return void
*/
public function forceDeleted(Category $blogCategory)
{
//
}
}
<file_sep>/app/Models/Category.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
const ROOT = 1;
protected $fillable = [
'title',
'slug',
'parent_id',
'description'
];
public function Post(){
return $this->hasMany(Post::class);
}
public function parentCategory(){
return $this->belongsTo(Category::class, 'parent_id', 'id');
}
public function getParentTitleAttribute(){
$title = $this->parentCategory->title
?? ($this->isRoot()
? 'Корінь'
: '???');
return $title;
}
public function isRoot(){
return $this->id === Category::ROOT;
}
public function scopeLastCategories($query, $count){
$categories = $query->orderBy('created_at','DESC')->take($count)->get();
return $categories;
}
}
<file_sep>/database/seeders/RoleSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class RoleSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$data = [
[
'role_name' => 'Админ'
],
[
'role_name' => 'Модератор'
],
[
'role_name' => 'Авторизований користувач'
],
];
DB::table('roles')->insert($data);
}
}
|
7b89f89cdc3c4bddb6379273bd23909e9b78f1a7
|
[
"PHP"
] | 13
|
PHP
|
OleksandrNechay/Blog
|
8cb453b25c04a9a92f6cd6009405d591ecd18a16
|
b84d6632c674c21f4d269cd04768fdc55d722ab2
|
refs/heads/master
|
<file_sep>#include "TitleScreen.h"
Screen::TitleScreen::TitleScreen(void)
{
}
Screen::TitleScreen::~TitleScreen(void)
{
}
void Screen::TitleScreen::LoadScreen(){
//make all entities for this screen and then put them into the entity manager
Entity::getEntityManager().clear();
Map::getMap().spawnEntities();
}
void Screen::TitleScreen::UnloadScreen()
{
//Entity::getEntityManager().clear();
}
void Screen::TitleScreen::Update(){
//Entity::getEntityManager().update();
if(System::getWindow().getKeyboard().anyKeyHit())
{
GameScreen* gameScreen;
gameScreen = new GameScreen();
ScreenManager::getInstance().LoadScreen(gameScreen);//switch to the Game Screen
}
}
void Screen::TitleScreen::Draw(System::Window &window){
Map::getMap().draw(System::getWindow());
Entity::getEntityManager().draw(window);
// Draw the string
window.drawText(Map::getMap().getPixelWidth()/2 - 260, 240, "Press A Key", 48, "PressStart2P.ttf");
}<file_sep>#pragma once
#include "Tmx.h"
#include "../System/Window.h"
#include "../Entity/Entity.h"
#include <iostream>
#include <string>
namespace Map
{
namespace colTile
{
enum cType
{
none = 0,
block
};
}
namespace spawnTile
{
enum sType
{
none = 0,
red,
blue,
duck
};
}
class Map
{
Tmx::Map map;
Map(){}
Map(Map const&);
void operator=(Map const&);
const Tmx::Layer* spawnLayer;
const Tmx::Layer* colLayer;
std::vector<const Tmx::Layer*> drawLayers;
Graphics::Sprite drawImage;
std::vector<Rect> world;
public:
static Map& getInstance()
{
static Map instance;
return instance;
}
int loadMap(std::string fileName);
void draw(System::Window& window);
void collide(Entity::Entity* entity);
int getWidth();
int getHeight();
int getTileWidth();
int getTileHeight();
int getPixelWidth();
int getPixelHeight();
colTile::cType getCollisionTile(Vector2f);
colTile::cType getCollisionTile(int x, int y);
void spawnEntities();
private:
const Tmx::Layer* getCollisionLayer();
const Tmx::Layer* getSpawnLayer();
void drawCollisionLayer(System::Window& window);
};
static Map& getMap()
{
return Map::getInstance();
}
}<file_sep>#ifndef COLLIDER_H
#define COLLIDER_H
#include "../Utility/Vector2f.h"
#include <stdlib.h>
namespace Entity
{
class Entity;
}
namespace Collision
{
enum Type
{
None,
AABB
};
class Collider
{
protected:
Type type;
Vector2f& position;
Entity::Entity* parent;
public:
Collider(Vector2f& pos, Entity::Entity* p = NULL)
:type(None),
position(pos),
parent(p)
{
}
virtual void collide(Collider* col)
{
}
Type getType()
{
return type;
}
Vector2f getPosition()
{
return position;
}
Entity::Entity* getParent()
{
return parent;
}
virtual ~Collider() {}
virtual void clearCollisionData() {}
};
}
#endif
#include "../Entity/Entity.h"<file_sep>#include <stdlib.h>
float randf();
float randf(float max);
float randf(float min, float max);<file_sep>#include "Mouse.h"
System::Mouse::Mouse()
{
for(int i = 0; i < Button::ButtonCount; i++)
{
buttons[i] = Button::msUp;
}
}
void System::Mouse::update()
{
for(int i = 0; i < Button::ButtonCount; i++)
{
if(buttons[i] == Button::msLetGo)
buttons[i] = Button::msUp;
else if(buttons[i] == Button::msHit)
buttons[i] = Button::msHeld;
}
}
void System::Mouse::onButtonPress(sf::Mouse::Button button)
{
buttons[button] = Button::msHit;
}
void System::Mouse::onButtonRelease(sf::Mouse::Button button)
{
buttons[button] = Button::msLetGo;
}
Vector2f System::Mouse::getMousePosition()
{
return Vector2f(sf::Mouse::getPosition().x, sf::Mouse::getPosition().y);
}
//returns true if key is was just pressed - edge sensitive
bool System::Mouse::buttonHit(Button::Button button)
{
return buttons[button] == Button::msHit;
}
//returns true if key is down
bool System::Mouse::buttonHeld(Button::Button button)
{
return buttons[button] == Button::msHit || buttons[button] == Button::msHeld;
}
//returns true ifkey is was just released - edge sensitive
bool System::Mouse::buttonLetGo(Button::Button button)
{
return buttons[button] == Button::msLetGo;
}
//returns true if key is up
bool System::Mouse::buttonUp(Button::Button button)
{
return buttons[button] == Button::msLetGo || buttons[button] == Button::msUp;
}
//returns true if any key is was just pressed - edge sensitive
bool System::Mouse::anyButtonHit()
{
for(int i = 0; i < Button::ButtonCount; i++)
{
if(buttonHit((Button::Button) i))
return true;
}
return false;
}
//returns true if any key is down
bool System::Mouse::anyButtonHeld()
{
for(int i = 0; i < Button::ButtonCount; i++)
{
if(buttonHeld((Button::Button) i))
return true;
}
return false;
}<file_sep>#ifndef ENTITY_H
#ifndef COLLIDER_H
#include "../Collision/Collider.h"
#else
#define ENTITY_H
#include "../Utility/Vector2f.h"
#include "../System/Window.h"
#include "../Utility/Rect.h"
#include "../Collision/AABBCollider.h"
namespace Entity
{
namespace Group
{
enum Group
{
none = 0,
red = 1,
blue = 2
};
}
namespace Direction
{
enum Direction
{
left = -1,
right = 1
};
}
class Entity
{
protected:
Rect body;
Vector2f velocity;
Vector2f heading;
float maxSpeed;
void clearCollisionData();
Collision::Collider* col;
bool remove;
bool ghost;
Group::Group group;
float health;
public:
Entity(float posX, float posY, float width, float height);
Entity(Rect rectBody);
virtual ~Entity() { delete col; }
virtual void update();
virtual void draw(System::Window& window);
virtual void hitWith(Entity* otherEntity) {}
virtual void onCollideLeft(Entity* other = NULL) {if(velocity.x < 0) velocity.x = 0;}
virtual void onCollideRight(Entity* other = NULL) {if(velocity.x > 0) velocity.x = 0;}
virtual void onCollideUp(Entity* other = NULL) {if(velocity.y < 0) velocity.y = 0;}
virtual void onCollideDown(Entity* other = NULL) {if(velocity.y > 0) velocity.y = 0;}
virtual void collideWith(Entity*);
virtual bool containsPoint(Vector2f);
virtual bool canOverlap(Entity* otherEntity);
virtual bool overlaps(Entity* otherEntity);
Vector2f getVelocity() const;
float getMaxSpeed() const;
bool isGhost() const;
bool shouldRemoveThis() const;
Rect getBody() const;
Vector2f getPosition() const;
Vector2f getCenter() const;
float getWidth() const;
float getHeight() const;
Vector2f setVelocity(Vector2f);
float setMaxSpeed(float);
bool setGhost(bool);
void removeThis();
Rect setBody(Rect);
Vector2f setPosition(Vector2f);
Vector2f setCenter(Vector2f);
float setWidth(float);
float setHeight(float);
virtual float takeDamage(float damage);
virtual float getHealth();
Vector2f getHeading();
Group::Group getGroup();
Collision::Collider* getCollider() {return col;}
void collide(Entity* entity);
};
}
#endif
#endif<file_sep>#pragma once
#include <string>
#include "Color.h"
#include <SFML/Graphics/Texture.hpp>
#ifndef WINDOW_H
namespace System
{
class Window;
}
#endif
namespace Graphics
{
class Image {
public:
Image();
Image(const std::string& filename);
void create(int width, int height);
void create(int width, int height, const Color &color);
void create(int width, int height, const unsigned char* pixels);
bool loadFromFile(const std::string& filename);
bool loadFromMemory(const void* data, std::size_t size);
bool saveToFile(const std::string name) const;
int getWidth() const;
int getHeight() const;
void setSmooth(bool smooth);
bool isSmooth();
void setRepeated(bool repeat);
bool isRepeated();
void setPixel(int x, int y, const Color& color);
void setPixels(const unsigned char* pixels, int width, int height, int x, int y);
Color getPixel(int x, int y) const;
const unsigned char* getPixelsPtr() const;
private:
sf::Texture img;
friend class System::Window;
friend class Sprite;
};
}
<file_sep>#include "Sound.h"
Audio::Sound::Sound(std::string file_name)
{
buffer = sf::SoundBuffer();
buffer.loadFromFile(file_name);
sound.setBuffer(buffer);
length = buffer.getDuration().asSeconds();
}
Audio::Sound::~Sound(void)
{
}
void Audio::Sound::Play(){
sound.play();
}
void Audio::Sound::Pause(){
sound.pause();
}
void Audio::Sound::Stop(){
sound.stop();
}
void Audio::Sound::setLooping(bool loops){
looping = loops;
sound.setLoop(loops);
}
bool Audio::Sound::getLooping(){
return looping;
}
void Audio::Sound::setPitch(float new_pitch){
pitch = new_pitch;
sound.setPitch(new_pitch);
}
float Audio::Sound::getPitch(){
return pitch;
}
void Audio::Sound::setVolume(float new_volume){
volume = new_volume;
sound.setVolume(new_volume);
}
float Audio::Sound::getVolume(){
return volume;
}
void Audio::Sound::setPlayingOffset(float new_offset){
offset = new_offset;
sf::Time t1 = sf::seconds(new_offset);
sound.setPlayingOffset(t1);
}
float Audio::Sound::getPlayingOffset(){
return sound.getPlayingOffset().asSeconds();
}
float Audio::Sound::getDuration(){
return length;
}<file_sep>#pragma once
namespace AI
{
// possible goal statuses
enum GoalStatus {inactive, active, completed, failed};
template <class EntityClass>
class Goal
{
protected:
EntityClass* owner;
GoalStatus status;
public:
virtual ~Goal() {}
Goal(EntityClass* owner);
// activates the goal
virtual void activate();
// processes the goal
virtual GoalStatus process();
// terminates the goal's processes
virtual void terminate();
// returns true if the goal is completed
virtual bool isComplete() const;
// returns true if the goal is active
virtual bool isActive() const;
// returns true if the goal is inactive
virtual bool isInactive() const;
// returns true if the goal has failed
virtual bool hasFailed() const;
// if the goal is inactive, the goal gets activated
virtual void activateIfInactive();
// if the goal has failed, reactive it
virtual void reactivateIfFailed();
};
}<file_sep>#include "main.h"
#include "Entity/Player.h"
#include "Entity/EntityManager.h"
#include "Screen/ScreenManager.h"
#include "Screen/GameScreen.h"
#include "Screen/TitleScreen.h"
#include "System/Window.h"
#include "System/Time.h"
#include "Map/Map.h"
#include "Audio\Music.h"
#include <iostream>
int main()
{
// Create the main window
System::Window::getInstance().initializeFullScreen(1920, 1080, "Atomic Duck Lord");
Map::getMap().loadMap("test.tmx");
Screen::TitleScreen* titleScreen;
titleScreen = new Screen::TitleScreen();
Screen::ScreenManager::getInstance().Initialize(titleScreen); //start at the titleScreen
System::Time& timer = System::Time::getInstance();
Graphics::Image redkeys("redkeys.png");
Graphics::Image bluekeys("bluekeys.png");
Audio::Music m("Spree_On.ogg");
m.setLooping(true);
m.Play();
srand(time(NULL));
// Start the game loop
while (System::Window::getInstance().isOpen())
{
// Process events
System::getWindow().update();
if(System::getWindow().getKeyboard().keyHit(System::Key::Escape))
{
System::getWindow().close();
return EXIT_SUCCESS;
}
//keep framerate below 60 fps
timer.maintainFPS(60);
// Update the Timer
timer.Update();
// fps calculation
//std::cout << 1/timer.unscaledDeltaTime() << std::endl;
Screen::ScreenManager::getInstance().Update();
// Clear screen
System::getWindow().clear();
// Draw the sprite
Screen::ScreenManager::getInstance().Draw(System::getWindow());
System::getWindow().drawImage(redkeys, Vector2f(70, 820), 4, 4);
System::getWindow().drawImage(bluekeys, Vector2f(1660, 820), 4, 4);
// Update the window
System::getWindow().display();
}
return EXIT_SUCCESS;
}<file_sep>#include "Music.h"
Audio::Music::Music(std::string file_name)
{
music.openFromFile(file_name);
length = music.getDuration().asSeconds();
}
Audio::Music::~Music(void)
{
}
void Audio::Music::Play(){
music.play();
}
void Audio::Music::Pause(){
music.pause();
}
void Audio::Music::Stop(){
music.stop();
}
void Audio::Music::setLooping(bool loops){
looping = loops;
music.setLoop(loops);
}
bool Audio::Music::getLooping(){
return looping;
}
void Audio::Music::setPitch(float new_pitch){
pitch = new_pitch;
music.setPitch(new_pitch);
}
float Audio::Music::getPitch(){
return pitch;
}
void Audio::Music::setVolume(float new_volume){
volume = new_volume;
music.setVolume(new_volume);
}
float Audio::Music::getVolume(){
return volume;
}
void Audio::Music::setPlayingOffset(float new_offset){
offset = new_offset;
sf::Time t1 = sf::seconds(new_offset);
music.setPlayingOffset(t1);
}
float Audio::Music::getPlayingOffset(){
return music.getPlayingOffset().asSeconds();
}
float Audio::Music::getDuration(){
return length;
}<file_sep>#include "GameScreen.h"
#include "../Entity/Duck.h"
Screen::GameScreen::GameScreen(void)
{
}
Screen::GameScreen::~GameScreen(void)
{
}
void Screen::GameScreen::LoadScreen()
{
Entity::Duck* duck = new Entity::Duck(Map::getMap().getPixelWidth()/2 - 19, 280, 38,40);
Entity::getEntityManager().add(duck);
}
void Screen::GameScreen::UnloadScreen()
{
//Entity::getEntityManager().clear();
}
void Screen::GameScreen::Update()
{
Entity::getEntityManager().update();
}
void Screen::GameScreen::Draw(System::Window& window)
{
Map::getMap().draw(System::getWindow());
Entity::getEntityManager().draw(window);
window.drawText(Map::getMap().getPixelWidth()/2 - 466, 60, "Fear Your Atomic Duck Lord", 36, "PressStart2P.ttf");
}<file_sep>-- lua script to load in values for the Rifle
name = "Rifle";
damage = 17;
range = 200;
accuracy = 0.174532925;
recoilUp = 1;
recoilDown = 1;
clipSize = 12;
rateOfFire = 10;
reloadSpeed = 1;
projectilesPerShot = 1;
-- Projectile Info
lifespan = 2;
speed = 1000;
dropOff = 0;
destroyOnImpact = true;
bounceLoss = 1;
AOE = false;
explodes = false;
automatic = true;<file_sep>#include "Duck.h"
#include "Nuke.h"
#include "EntityManager.h"
#include "../Utility/randf.h"
Entity::Duck::Duck(float posX,float posY,float width,float height)
:Entity(posX, posY, width, height),
image("duck.png"),
countdown("beep.wav"),
bounceSound("squeak.wav"),
hitSound("squawk.wav")
{
col = new Collision::AABBCollider(body, this);
maxSpeed = 400;
jumpPower = 750;
if(rand() & 1 == 1)
{
unscaledVelocity.x = maxSpeed;
unscaledVelocity.y = jumpPower * randf(-3,.3);
heading.x = Direction::right;
}
else
{
unscaledVelocity.x = -maxSpeed;
unscaledVelocity.y * jumpPower * randf(-3,.3);
heading.x = Direction::left;
}
timeOfDeath = System::Time::getInstance().time() + 20;
}
void Entity::Duck::update()
{
setPosition(getPosition() + velocity);
rotation += 720 * System::Time::getInstance().unscaledDeltaTime() * heading.x;
if(!static_cast<Collision::AABBCollider*>(col)->getCollideDown())
unscaledVelocity.y += 400 * System::Time::getInstance().unscaledDeltaTime();
velocity.clampX(maxSpeed);
velocity.clampY(jumpPower);
velocity = unscaledVelocity * System::Time::getInstance().unscaledDeltaTime();
if(timeOfDeath <= System::Time::getInstance().time())
{
static bool flag = true;
if(flag)
{
countdown.Play();
flag = false;
}
if(!countdown.isPlaying())
{
removeThis();
EntityManager::getInstance().add(new Nuke(getCenter().x));
flag = true;
}
}
}
void Entity::Duck::draw(System::Window& window)
{
window.drawImage(image, getPosition(), heading.x, 1, rotation);
}
void Entity::Duck::onCollideLeft(Entity* other)
{
if(other != NULL)
{
velocity.x = 0;
unscaledVelocity.x = maxSpeed;
unscaledVelocity.y -= 2*jumpPower/3;
hitSound.setPitch(randf(.7, 1.3));
hitSound.Play();
}
else if(velocity.x < 0)
{
velocity.x = 0;
unscaledVelocity.x = abs(unscaledVelocity.x * .75);
unscaledVelocity.y -= jumpPower/3;
bounceSound.setPitch(randf(.7, 1.3));
bounceSound.Play();
}
heading.x = Direction::right;
}
void Entity::Duck::onCollideRight(Entity* other)
{
if(other != NULL)
{
velocity.x = 0;
unscaledVelocity.x = -maxSpeed;
unscaledVelocity.y -= 2*jumpPower/3;
hitSound.setPitch(randf(.7, 1.3));
hitSound.Play();
}
else if(velocity.x > 0)
{
velocity.x = 0;
unscaledVelocity.x = -abs(unscaledVelocity.x * .75);
unscaledVelocity.y -= jumpPower/3;
bounceSound.setPitch(randf(.7, 1.3));
bounceSound.Play();
}
heading.x = Direction::left;
}
void Entity::Duck::onCollideUp(Entity* other)
{
if(other != NULL)
{
velocity.y = 0;
unscaledVelocity.y = -jumpPower;
if(getCenter().x > other->getCenter().x)
{
unscaledVelocity.x = maxSpeed;//2*maxSpeed/3;
}
else
{
unscaledVelocity.x = -maxSpeed;//2*maxSpeed/3;
}
hitSound.setPitch(randf(.7, 1.3));
hitSound.Play();
}
else if(velocity.y < 0)
{
velocity.y = 0;
unscaledVelocity.y = abs(unscaledVelocity.y *.6);
bounceSound.setPitch(randf(.7, 1.3));
bounceSound.Play();
}
}
void Entity::Duck::onCollideDown(Entity* other)
{
if(other != NULL)
{
velocity.y = 0;
unscaledVelocity.y = jumpPower;
if(getCenter().x > other->getCenter().x)
{
unscaledVelocity.x = maxSpeed;//2*maxSpeed/3;
}
else
{
unscaledVelocity.x = -maxSpeed;//2*maxSpeed/3;
}
hitSound.setPitch(randf(.7, 1.3));
hitSound.Play();
}
else if(velocity.y > 0)
{
velocity.y = 0;
unscaledVelocity.y = -abs(unscaledVelocity.y *.8);
bounceSound.setPitch(randf(.7, 1.3));
bounceSound.Play();
}
}<file_sep>#ifndef MOUSE_H
#define MOUSE_H
#include <SFML/Graphics.hpp>
#include "../Utility/Vector2f.h"
namespace System
{
namespace Button
{
enum Button
{
Left,
Right,
Middle,
XButton1,
XButton2,
ButtonCount
};
enum ButtonState
{
msUp = 0,
msHit,
msHeld,
msLetGo,
};
}
#if !defined(WINDOW_H) && !defined(KEYBOARD_H)
class Window;
#endif
class Mouse
{
friend class Window;
Button::ButtonState buttons[Button::ButtonCount];
Mouse();
void update();
void onButtonPress(sf::Mouse::Button button);
void onButtonRelease(sf::Mouse::Button button);
void operator=(Mouse const&);
public:
Vector2f getMousePosition();
//returns true if key is was just pressed - edge sensitive
bool buttonHit(Button::Button button);
//returns true if key is down
bool buttonHeld(Button::Button button);
//returns true ifkey is was just released - edge sensitive
bool buttonLetGo(Button::Button button);
//returns true if key is up
bool buttonUp(Button::Button button);
//returns true if any key is was just pressed - edge sensitive
bool anyButtonHit();
//returns true if any key is down
bool anyButtonHeld();
};
}
#endif
<file_sep>#pragma once
#include <math.h>
class Vector2f
{
public:
float x;
float y;
Vector2f() :x(0), y(0) {}
Vector2f(float xcoord, float ycoord) : x(xcoord), y(ycoord) {}
float dot(Vector2f const& v);
Vector2f operator=(Vector2f const&);
Vector2f operator+=(Vector2f const&);
Vector2f operator-=(Vector2f const&);
Vector2f operator*=(float const&);
Vector2f operator+(Vector2f const&) const;
Vector2f operator-(Vector2f const&) const;
Vector2f operator*(float) const;
Vector2f SetValues(float, float);
Vector2f flip();
float magnitude();
float magnitudeSquared();
float length(Vector2f vec);
float lengthSquared(Vector2f vec);
// Makes the vector have a magnitude of 1
Vector2f normalize();
// Clamps the velocity to a max speed
Vector2f clamp(float MaxSpeed);
// Clamps the x part of the velocity to a max speed
Vector2f clampX(float MaxSpeed);
// Clamps the y part of the velocity to a max speed
Vector2f clampY(float MaxSpeed);
//Rotates the Vector in radians
Vector2f rotate(float);
Vector2f zero();
};<file_sep>-- lua script to load in values for the Rifle
name = "Pistol";
damage = 15;
range = 200;
accuracy = 0.174532925;
recoilUp = 1;
recoilDown = 1;
clipSize = 12;
rateOfFire = 5;
reloadSpeed = 1;
projectilesPerShot = 1;
-- Projectile Info
lifespan = 2;
speed = 1000;
dropOff = 0;
destroyOnImpact = true;
bounceLoss = 1;
AOE = false;
explodes = false;
automatic = false;<file_sep>#include "Color.h"
Graphics::Color::Color() : r(0), g(0), b(0), a(255) {
}
Graphics::Color::Color(int red, int green, int blue, int alpha=255) {
r = clamp(red);
g = clamp(green);
b = clamp(blue);
a = clamp(alpha);
}
bool Graphics::Color::operator ==(const Color& right) {
return (this->r == right.r && this->g == right.g && this->b == right.b && this->a == right.a);
}
bool Graphics::Color::operator !=(const Color& right) {
return !(this->r == right.r && this->g == right.g && this->b == right.b && this->a == right.a);
}
Graphics::Color Graphics::Color::operator +(const Color& right) {
return Color(this->a+right.a, this->g+right.g, this->b+right.b, this->a+right.a);
}
Graphics::Color Graphics::Color::operator *(const Color& right) {
return Color(this->a*right.a, this->g*right.g, this->b*right.b, this->a*right.a);
}
Graphics::Color& Graphics::Color::operator +=(const Color& right) {
*this = *this + right;
return *this;
}
Graphics::Color& Graphics::Color::operator *=(const Color& right) {
*this = *this * right;
return *this;
}
int Graphics::Color::clamp(int value) {
if(value < MIN_COLOR) {
return MIN_COLOR;
}
if(value > MAX_COLOR) {
return MAX_COLOR;
}
return value;
}
const Graphics::Color Graphics::Color::Black = Color(0, 0, 0);
const Graphics::Color Graphics::Color::White = Color(255, 255, 255);
const Graphics::Color Graphics::Color::Red = Color(255, 0, 0);
const Graphics::Color Graphics::Color::Green = Color(0, 255, 0);
const Graphics::Color Graphics::Color::Blue = Color(0, 0, 255);
const Graphics::Color Graphics::Color::Yellow = Color(255, 255, 0);
const Graphics::Color Graphics::Color::Magenta = Color(255, 0, 255);
const Graphics::Color Graphics::Color::Cyan = Color(0, 255, 255);
const Graphics::Color Graphics::Color::Transparent = Color(0, 0, 0, 0);
<file_sep>#ifndef TIME_H
#define TIME_H
#include "SFML\System.hpp"
#include <chrono>
#include <thread>
namespace System
{
class Time
{
public:
~Time(void);
float time(void);
float deltaTime(void);
float timeScale(void);
float unscaledTime(void);
float unscaledDeltaTime(void);
void setTimeScale(float);
void resetTime(void);
void maintainFPS(int fpsmax);
void Update(void);
void modifyTimeScale(float percent);
//Time is a singleton class
static Time& getInstance()
{
static Time instance;
return instance;
}
private:
Time(void);
Time(Time const&);
void operator=(Time const&);
sf::Clock clock;
float current_time;
float delta_time;
float time_scale;
float unscaled_time;
float unscaled_delta_time;
};
}
#endif //TIME_H
<file_sep>#include "Time.h"
System::Time::Time(void)
: current_time(clock.getElapsedTime().asSeconds()),
unscaled_time(clock.getElapsedTime().asSeconds()),
time_scale(1),
delta_time(0),
unscaled_delta_time(0)
{
}
System::Time::~Time(void)
{
}
float System::Time::time(){
return current_time;
}
float System::Time::timeScale(){
return time_scale;
}
float System::Time::deltaTime(){
return delta_time;
}
float System::Time::unscaledTime(){
return unscaled_time;
}
float System::Time::unscaledDeltaTime(){
return unscaled_delta_time;
}
void System::Time::setTimeScale(float scale){
time_scale = scale;
}
void System::Time::modifyTimeScale(float percent){
time_scale *= percent;
}
void System::Time::resetTime(){
current_time = 0;
}
void System::Time::maintainFPS(int fpsmax){
if((1/(clock.getElapsedTime().asSeconds() - unscaled_time))>fpsmax){
long int us = (1000000/fpsmax + 1 - long int ((clock.getElapsedTime().asSeconds() - unscaled_time)*1000000));
std::this_thread::sleep_for(std::chrono::microseconds(us));
}
}
void System::Time::Update(){
float time_tmp = clock.getElapsedTime().asSeconds();
unscaled_delta_time = time_tmp-unscaled_time;
unscaled_time = time_tmp;
delta_time = unscaled_delta_time*time_scale;
current_time += delta_time;
}
<file_sep>#ifndef ENDSCREEN_H
#define ENDSCREEN_H
#include "Screen.h"
#include "../Entity/EntityManager.h"
#include "ScreenManager.h"
namespace Screen
{
class EndScreen:public Screen
{
public:
EndScreen(void);
~EndScreen(void);
void LoadScreen();
void UnloadScreen();
void Update();
void Draw(System::Window &window);
private:
float timeOfDeath;
int result;
};
}
#endif<file_sep>#ifndef MUSIC_H
#define MUSIC_H
#include "SFML\Audio.hpp"
namespace Audio
{
class Music
{
public:
Music(std::string file_name);
~Music(void);
void Play();
void Pause();
void Stop();
void setLooping(bool loops);
bool getLooping();
void setPitch(float new_pitch);
float getPitch();
void setVolume(float new_volume);
float getVolume();
void setPlayingOffset(float new_offset);
float getPlayingOffset();
float getDuration();
private:
sf::Music music;
float volume;
float pitch;
float length;
float offset;
bool looping;
bool playing;
};
}
#endif<file_sep>#include "Entity.h"
Entity::Entity::Entity(float posX,float posY,float width,float height)
:body(posX, posY, width, height),
velocity(0, 0),
col(new Collision::AABBCollider(body, this)),
remove(false),
group(Group::none),
health(100),
ghost(false)
{
clearCollisionData();
}
Entity::Entity::Entity(Rect rectBody)
:body(rectBody),
velocity(0, 0),
col(new Collision::AABBCollider(body, this)),
remove(false),
group(Group::none),
health(100),
ghost(false)
{
clearCollisionData();
}
void Entity::Entity::update()
{
body.setTopLeft(body.getTopLeft() + velocity);
}
void Entity::Entity::draw(System::Window& window)
{
window.drawRect(body);
}
void Entity::Entity::clearCollisionData()
{
col->clearCollisionData();
}
void Entity::Entity::collideWith(Entity* other)
{
col->collide(other->col);
}
bool Entity::Entity::containsPoint(Vector2f point)
{
return body.containsPoint(point);
}
bool Entity::Entity::canOverlap(Entity* otherEntity)
{
return !isGhost() && !otherEntity->isGhost() && (group != otherEntity->group);
}
bool Entity::Entity::overlaps(Entity* otherEntity)
{
return body.overlaps(otherEntity->getBody());
}
Vector2f Entity::Entity::getVelocity() const
{
return velocity;
}
float Entity::Entity::getMaxSpeed() const
{
return maxSpeed;
}
bool Entity::Entity::isGhost() const
{
return ghost;
}
bool Entity::Entity::shouldRemoveThis() const
{
return remove;
}
Rect Entity::Entity::getBody() const
{
return body;
}
Vector2f Entity::Entity::getPosition() const
{
return body.getTopLeft();
}
Vector2f Entity::Entity::getCenter() const
{
return body.getCenter();
}
float Entity::Entity::getWidth() const
{
return body.getWidth();
}
float Entity::Entity::getHeight() const
{
return body.getHeight();
}
Vector2f Entity::Entity::setVelocity(Vector2f vel)
{
velocity = vel;
return vel;
}
float Entity::Entity::setMaxSpeed(float speed)
{
maxSpeed = speed;
return speed;
}
bool Entity::Entity::setGhost(bool isGhost)
{
ghost = isGhost;
return ghost;
}
void Entity::Entity::removeThis()
{
remove = true;
}
Rect Entity::Entity::setBody(Rect newBody)
{
body = newBody;
return newBody;
}
Vector2f Entity::Entity::setPosition(Vector2f position)
{
body.setTopLeft(position);
return position;
}
Vector2f Entity::Entity::setCenter(Vector2f position)
{
body.setCenter(position);
return position;
}
float Entity::Entity::setWidth(float width)
{
body.setWidth(width);
return width;
}
float Entity::Entity::setHeight(float height)
{
body.setHeight(height);
return height;
}
Vector2f Entity::Entity::getHeading()
{
return heading;
}
Entity::Group::Group Entity::Entity::getGroup()
{
return group;
}
float Entity::Entity::takeDamage(float damage)
{
health -= damage;
if(health <= 0)
removeThis();
return health;
}
float Entity::Entity::getHealth()
{
return health;
}
void Entity::Entity::collide(Entity* entity)
{
col->collide(entity->col);
}
<file_sep>#include "Map.h"
#include "../Entity/Player.h"
#include "../Entity/Duck.h"
#include "../Entity/EntityManager.h"
int Map::Map::loadMap(std::string fileName)
{
map.ParseFile(fileName);
if (map.HasError())
{
std::cout << "error code: " << map.GetErrorCode() << std::endl;
std::cout << "error text: " << map.GetErrorText() << std::endl;
return map.GetErrorCode();
}
for (int i = 0; i < map.GetNumLayers(); ++i)
{
if(map.GetLayer(i)->GetName() == "collision")
colLayer = map.GetLayer(i);
else if(map.GetLayer(i)->GetName() == "spawn")
spawnLayer = map.GetLayer(i);
else
drawLayers.push_back(map.GetLayer(i));
}
drawImage.setSpriteSheet("tiles.png");
drawImage.addFrames(getTileWidth(), getTileHeight());
//spawnEntities();
if(world.empty())
{
world.push_back(Rect(0, 0, 1920, 180));
world.push_back(Rect(0, 160, 40, 400));
world.push_back(Rect(1880, 160, 40, 400));
world.push_back(Rect(1720, 560, 160, 320));
world.push_back(Rect(1560, 720, 160, 160));
world.push_back(Rect(40, 560, 160, 320));
world.push_back(Rect(200, 720, 160, 160));
world.push_back(Rect(0, 880, 1920, 200));
world.push_back(Rect(360, 400, 320, 80));
world.push_back(Rect(840, 640, 240, 80));
world.push_back(Rect(1240, 400, 320, 80));
}
return 0;
}
void Map::Map::draw(System::Window& window)
{
//drawCollisionLayer(window);
const Tmx::Layer* layer = drawLayers[0];
if(layer != NULL)
{
for(int i = 0; i < layer->GetWidth(); i++)
{
for(int j = 0; j < layer->GetHeight(); j++)
{
if(layer->GetTile(i, j).id > 0)
{
Vector2f pos(i * getTileWidth(), j * getTileHeight());
window.drawSprite(drawImage, pos, layer->GetTile(i, j).id);
}
}
}
}
}
void Map::Map::collide(Entity::Entity* entity)
{
for(int i = 0; i < world.size(); i++)
{
Collision::AABBCollider tile(world[i]);
entity->getCollider()->collide(&tile);
}
/*
int ymin = (entity->getBody().getTop() + entity->getVelocity().y) / getTileHeight();
int ymax = (entity->getBody().getBottom() + entity->getVelocity().y) / getTileHeight() + 1;
int xmin = (entity->getBody().getLeft() + entity->getVelocity().x) / getTileWidth();
int xmax = (entity->getBody().getRight() + entity->getVelocity().x) / getTileWidth() + 1;
for(int y = ymin; y < ymax; y++)
{
for(int x = xmin; x < xmax; x++)
{
if( y < getHeight() && x < getWidth() && y >= 0 && x >= 0 && getCollisionLayer()->GetTile(x, y).id != colTile::none)
{
Collision::AABBCollider tile(Rect(x * getTileWidth(), y * getTileHeight(), getTileWidth(), getTileHeight()));
entity->getCollider()->collide(&tile);
}
}
}*/
}
int Map::Map::getWidth()
{
return map.GetWidth();
}
int Map::Map::getHeight()
{
return map.GetHeight();
}
int Map::Map::getTileWidth()
{
return map.GetTileWidth();
}
int Map::Map::getTileHeight()
{
return map.GetTileHeight();;
}
int Map::Map::getPixelWidth()
{
return map.GetWidth() * map.GetTileWidth();
}
int Map::Map::getPixelHeight()
{
return map.GetHeight() * map.GetTileHeight();
}
const Tmx::Layer* Map::Map::getCollisionLayer()
{
return colLayer;
}
const Tmx::Layer* Map::Map::getSpawnLayer()
{
return spawnLayer;
}
void Map::Map::drawCollisionLayer(System::Window& window)
{
const Tmx::Layer* layer = getCollisionLayer();
if(layer != NULL)
{
for(int i = 0; i < layer->GetWidth(); i++)
{
for(int j = 0; j < layer->GetHeight(); j++)
{
if(layer->GetTile(i, j).id != colTile::none)
{
window.drawRect(i * getTileWidth(), j * getTileHeight(), getTileWidth(), getTileHeight());
}
}
}
}
}
void Map::Map::spawnEntities()
{
const Tmx::Layer* layer = getSpawnLayer();
if(layer != NULL)
{
for(int j = 0; j < layer->GetHeight(); j++)
{
for(int i = 0; i < layer->GetWidth(); i++)
{
Entity::Player* player;
Entity::Duck* duck;
switch(layer->GetTile(i, j).id)
{
case spawnTile::red:
player = new Entity::Player(i*getTileWidth(), j*getTileHeight(), 45,80, Entity::Group::red);
Entity::getEntityManager().add(player);
break;
case spawnTile::blue:
player = new Entity::Player(i*getTileWidth(), j*getTileHeight(), 45,80, Entity::Group::blue);
Entity::getEntityManager().add(player);
break;
case spawnTile::duck:
duck = new Entity::Duck(i*getTileWidth(), j*getTileHeight(), 38,40);
Entity::getEntityManager().add(duck);
break;
}
}
}
}
}
Map::colTile::cType Map::Map::getCollisionTile(Vector2f position)
{
const Tmx::Layer* col = getCollisionLayer();
return (colTile::cType) col->GetTile(position.x, position.y).id;
}
Map::colTile::cType Map::Map::getCollisionTile(int x, int y)
{
const Tmx::Layer* col = getCollisionLayer();
return (colTile::cType) col->GetTile(x, y).id;
}<file_sep>AtomicDuckLord
==============
<file_sep>#pragma once
#include "Collider.h"
#include "../Utility/Rect.h"
namespace Collision
{
class AABBCollider: public Collider
{
Rect& box;
bool collideRight;
bool collideLeft;
bool collideDown;
bool collideUp;
public:
AABBCollider(Rect& body, Entity::Entity* p = NULL);
void collide(Collider* col);
void AABBCollision(AABBCollider* col);
Type getType();
Vector2f getPosition();
Rect getBody();
void clearCollisionData();
bool getCollideRight();
bool getCollideLeft();
bool getCollideDown();
bool getCollideUp();
};
}<file_sep>#include "EndScreen.h"
#include "TitleScreen.h"
#include "../Entity/Duck.h"
Screen::EndScreen::EndScreen(void)
{
timeOfDeath = System::Time::getInstance().time() + 3;
}
Screen::EndScreen::~EndScreen(void)
{
}
void Screen::EndScreen::LoadScreen()
{
if(Entity::getEntityManager().getRed() == NULL || Entity::getEntityManager().getRed()->shouldRemoveThis())
if(Entity::getEntityManager().getBlue() == NULL || Entity::getEntityManager().getBlue()->shouldRemoveThis())
result = 3;
else
result = 2;
else if(Entity::getEntityManager().getBlue() == NULL || Entity::getEntityManager().getBlue()->shouldRemoveThis())
result = 1;
else result = 0;
}
void Screen::EndScreen::UnloadScreen()
{
}
void Screen::EndScreen::Update()
{
Entity::getEntityManager().update();
if(timeOfDeath <= System::Time::getInstance().time())
{
getScreenManager().LoadScreen(new TitleScreen());
}
}
void Screen::EndScreen::Draw(System::Window& window)
{
Map::getMap().draw(System::getWindow());
Entity::getEntityManager().draw(window);
switch(result)
{
case 1:
window.drawText(Map::getMap().getPixelWidth()/2 - 170, 240, "Red Wins", 48, "PressStart2P.ttf");
break;
case 2:
window.drawText(Map::getMap().getPixelWidth()/2 - 210, 240, "Blue Wins", 48, "PressStart2P.ttf");
break;
case 3:
window.drawText(Map::getMap().getPixelWidth()/2 - 335, 240, "Duck Lord Wins", 48, "PressStart2P.ttf");
break;
default:
window.drawText(Map::getMap().getPixelWidth()/2 - 100, 240, "Sod Off", 48, "PressStart2P.ttf");
}
}<file_sep>#include "EntityManager.h"
#include "../Map/Map.h"
#include <iostream>
Entity::Player* Entity::EntityManager::getRed()
{
return red;
}
Entity::Player* Entity::EntityManager::getBlue()
{
return blue;
}
void Entity::EntityManager::clear()
{
for(unsigned int i = 0; i < entities.size(); i++)
{
if(entities[i] != NULL)
{
delete entities[i];
}
}
entities.clear();
}
void Entity::EntityManager::update()
{
for (unsigned int i = 0; i < entities.size(); i++)
{
if(entities[i] != NULL)
{
entities[i]->update();
entities[i]->getCollider()->clearCollisionData();
}
}
collide();
cull();
}
void Entity::EntityManager::add(Entity* entity)
{
if(dynamic_cast<Player*>(entity) != NULL)
if(entity->getGroup() == Group::red)
red = dynamic_cast<Player*>(entity);
else
blue = dynamic_cast<Player*>(entity);
entities.push_back(entity);
}
void Entity::EntityManager::draw(System::Window& window)
{
for (unsigned int i = 0; i < entities.size(); i++)
{
if(entities[i] != NULL)
{
entities[i]->draw(window);
}
}
}
void Entity::EntityManager::collide()
{
for (unsigned int i = 0; i < entities.size(); i++)
{
if(entities[i] != NULL)
{
Map::getMap().collide(entities[i]);
for (unsigned int j = i+1; j < entities.size(); j++)
{
if(entities[i]->canOverlap(entities[j]))
entities[i]->collide(entities[j]);
/*else if(entities[j] != NULL && entities[i]->canOverlap(entities[j]))
{
if(entities[i]->overlaps(entities[j]))
{
entities[i]->hitWith(entities[j]);
entities[j]->hitWith(entities[i]);
}
}*/
}
}
}
}
void Entity::EntityManager::cull()
{
for (unsigned int i = 0; i < entities.size(); i++)
{
if(entities[i] != NULL)
{
if(entities[i]->shouldRemoveThis())
{
if(entities[i] == red)
red = NULL;
if(entities[i] == blue)
blue = NULL;
delete entities[i];
entities.erase(entities.begin() + i);
i--;
}
}
}
}<file_sep>#ifndef SCREEN_H
#define SCREEN_H
#include "../System/Window.h"
#include "../Map/Map.h"
namespace Screen
{
class Screen
{
public:
Screen(void);
virtual ~Screen(void);
virtual void LoadScreen();
virtual void UnloadScreen();
virtual void Update();
virtual void Draw(System::Window &window);
};
}
#endif<file_sep>#pragma once
#include "Entity.h"
#include "../Collision/AABBCollider.h"
#include "../System/Time.h"
#include "../Graphics/Image.h"
#include "../Audio/Sound.h"
namespace Entity
{
class Player : public Entity
{
Vector2f unscaledVelocity;
Graphics::Image img;
Audio::Sound jumpSound;
Audio::Sound collideSound;
public:
Player(float posX,float posY,float width,float height, Group::Group team);
void update();
void draw(System::Window&);
void onCollideLeft(Entity* other = NULL);
void onCollideRight(Entity* other = NULL);
void onCollideUp(Entity* other = NULL);
void onCollideDown(Entity* other = NULL);
private:
void boundsCheck();
};
}<file_sep>#include "Window.h"
unsigned int System::Window::GetWidth() const
{
return window.getSize().x;
}
unsigned int System::Window::GetHeight() const
{
return window.getSize().y;
}
bool System::Window::drawText(Vector2f position, std::string text, int size, std::string font)
{
sf::Font sffont;
if (!sffont.loadFromFile(font))
return false;
sf::Text sftext(text, sffont, size);
sftext.setPosition(globalXScale * position.x,globalYScale * position.y);
sftext.setScale(globalXScale, globalYScale);
window.draw(sftext);
return true;
}
bool System::Window::drawText(float posX, float posY, std::string text, int size, std::string font)
{
sf::Font sffont;
if (!sffont.loadFromFile(font))
return false;
sf::Text sftext(text, sffont, size);
sftext.setPosition(posX * globalXScale, posY * globalYScale);
sftext.setScale(globalXScale, globalYScale);
window.draw(sftext);
return true;
}
bool System::Window::drawRect(Rect rect)
{
sf::RectangleShape sfrect = sf::RectangleShape(sf::Vector2f(rect.getWidth(), rect.getHeight()));
sfrect.setFillColor(sf::Color::Magenta);
sfrect.setPosition(rect.getLeft() * globalXScale, rect.getTop() * globalYScale);
sfrect.setScale(globalXScale, globalYScale);
window.draw(sfrect);
return true;
}
bool System::Window::drawRect(float posX, float posY, float width, float height)
{
sf::RectangleShape sfrect = sf::RectangleShape(sf::Vector2f(width, height));
sfrect.setFillColor(sf::Color::Magenta);
sfrect.setPosition(posX * globalXScale, posY * globalYScale);
sfrect.setScale(globalXScale, globalYScale);
window.draw(sfrect);
return true;
}
bool System::Window::drawSprite(Graphics::Sprite sprite, Vector2f position, int frame)
{
sf::Sprite sp(sprite.tex->img);
Rect r = sprite.getFrame(frame);
sp.setTextureRect(sf::IntRect(r.getLeft(), r.getTop(), r.getWidth(), r.getHeight()));
sp.setPosition(position.x * globalXScale, position.y * globalYScale);
sp.setScale(globalXScale, globalYScale);
window.draw(sp);
return true;
}
bool System::Window::drawImage(Graphics::Image image, Vector2f position, float scaleX, float scaleY, float degrees)
{
sf::Sprite sprite(image.img);
sprite.setPosition((position.x + (scaleX<0) * -scaleX * image.getWidth()) * globalXScale, (position.y + (scaleY<0) * -scaleY * image.getHeight()) * globalYScale);
sprite.setScale(scaleX * globalXScale, scaleY * globalYScale);
// sprite.setRotation(degrees);
window.draw(sprite);
return true;
}
void System::Window::clear()
{
window.clear();
}
void System::Window::display()
{
window.display();
}
bool System::Window::isOpen()
{
return window.isOpen();
}
void System::Window::update()
{
keyboard.update();
mouse.update();
// Process events
sf::Event event;
while (window.pollEvent(event))
{
// Close window : exit
if (event.type == sf::Event::Closed)
{
window.close();
}
else if (event.type == sf::Event::KeyPressed)
{
keyboard.onKeyPress(event.key.code);
}
else if (event.type == sf::Event::KeyReleased)
{
keyboard.onKeyRelease(event.key.code);
}
else if (event.type == sf::Event::MouseButtonPressed)
{
mouse.onButtonPress(event.mouseButton.button);
}
else if (event.type == sf::Event::MouseButtonReleased)
{
mouse.onButtonRelease(event.mouseButton.button);
}
}
}
void System::Window::close()
{
if(window.isOpen())
window.close();
}
System::Keyboard& System::Window::getKeyboard()
{
return keyboard;
}
System::Mouse& System::Window::getMouse()
{
return mouse;
}
void System::Window::initialize(unsigned int width, unsigned int height, std::string name)
{
window.create(sf::VideoMode(width, height), name);
globalXScale = window.getSize().x / 1920.0;
globalYScale = window.getSize().y / 1080.0;
}
void System::Window::initializeFullScreen(unsigned int width, unsigned int height, std::string name)
{
window.create(sf::VideoMode(width, height), name, sf::Style::Fullscreen);
globalXScale = window.getSize().x / 1920.0;
globalYScale = window.getSize().y / 1080.0;
}
<file_sep>#pragma once
#include "Entity.h"
#include "../Collision/AABBCollider.h"
#include "../System/Time.h"
#include "../Graphics/Image.h"
#include "../Audio/Sound.h"
namespace Entity
{
class Duck : public Entity
{
Vector2f unscaledVelocity;
Graphics::Image image;
float jumpPower;
float timeOfDeath;
float rotation;
Audio::Sound bounceSound;
Audio::Sound hitSound;
Audio::Sound countdown;
public:
Duck(float posX,float posY,float width,float height);
void update();
void draw(System::Window&);
void onCollideLeft(Entity* other = NULL);
void onCollideRight(Entity* other = NULL);
void onCollideUp(Entity* other = NULL);
void onCollideDown(Entity* other = NULL);
};
}<file_sep>#include "Player.h"
#include "EntityManager.h"
#include "../Map/Map.h"
#include "../Utility/randf.h"
Entity::Player::Player(float posX,float posY,float width,float height, Group::Group team)
:Entity(posX, posY, width, height),
jumpSound((team == Group::red)? "red_jump.wav" : "blue_jump.wav"),
collideSound((team == Group::red)? "red_collide.wav" : "blue_collide.wav")
{
col = new Collision::AABBCollider(body, this);
maxSpeed = 450;
group = team;
if(group == Group::red)
img.loadFromFile("red.png");
else
img.loadFromFile("blue.png");
if(group == Group::red)
heading.x = Direction::right;
else
heading.x = Direction::left;
}
void Entity::Player::update()
{
setPosition(getPosition() + velocity);
unscaledVelocity.x = 0;
System::Keyboard keyboard = System::Window::getInstance().getKeyboard();
if(group == Group::red)
{
if(keyboard.keyHeld(System::Key::A))
{
unscaledVelocity.x -= maxSpeed;
heading.x = Direction::left;
}
if(keyboard.keyHeld(System::Key::D))
{
unscaledVelocity.x += maxSpeed;
heading.x = Direction::right;
}
if(static_cast<Collision::AABBCollider*>(col)->getCollideDown())
{
if(keyboard.keyHeld(System::Key::W))
{
unscaledVelocity.y -= 600;
jumpSound.setPitch(randf(.7, 1.3));
jumpSound.setVolume(17);
jumpSound.Play();
}
}
else
unscaledVelocity.y += 550 * System::Time::getInstance().unscaledDeltaTime();
}
else if(group == Group::blue)
{
if(keyboard.keyHeld(System::Key::L))
{
unscaledVelocity.x += maxSpeed;
heading.x = Direction::right;
}
if(keyboard.keyHeld(System::Key::J))
{
unscaledVelocity.x -= maxSpeed;
heading.x = Direction::left;
}
if(static_cast<Collision::AABBCollider*>(col)->getCollideDown())
{
if(keyboard.keyHeld(System::Key::I))
{
unscaledVelocity.y -= 600;
jumpSound.setPitch(randf(.7, 1.3));
jumpSound.setVolume(37);
jumpSound.Play();
}
}
else
unscaledVelocity.y += 550 * System::Time::getInstance().unscaledDeltaTime();
}
velocity = unscaledVelocity * System::Time::getInstance().unscaledDeltaTime();
boundsCheck();
}
void Entity::Player::draw(System::Window& window)
{
//window.drawRect(body);
window.drawImage(img, getPosition(), heading.x, 1.0);
}
void Entity::Player::onCollideLeft(Entity* other)
{
if(velocity.x < 0)
{
velocity.x = 0;
unscaledVelocity.x = 0;
}
}
void Entity::Player::onCollideRight(Entity* other)
{
if(velocity.x > 0)
{
velocity.x = 0;
unscaledVelocity.x = 0;
}
}
void Entity::Player::onCollideUp(Entity* other)
{
if(velocity.y < 0)
{
velocity.y = 0;
unscaledVelocity.y = 0;
if(other == NULL)
{
collideSound.setPitch(randf(.7, 1.3));
collideSound.Play();
}
}
}
void Entity::Player::onCollideDown(Entity* other)
{
if(velocity.y > 0)
{
velocity.y = 0;
unscaledVelocity.y = 0;
if(other == NULL)
{
collideSound.setPitch(randf(.7, 1.3));
collideSound.Play();
}
}
}
void Entity::Player::boundsCheck()
{
if(group == Group::red)
{
if(getBody().getRight() + velocity.x >= Map::getMap().getPixelWidth()/2)
{
velocity.x = 0;
Vector2f v = getPosition();
v.x = Map::getMap().getPixelWidth()/2 - getWidth();
setPosition(v);
}
}
else if(group == Group::blue)
{
if(getBody().getLeft() + velocity.x < Map::getMap().getPixelWidth()/2)
{
velocity.x = 0;
Vector2f v = getPosition();
v.x = Map::getMap().getPixelWidth()/2;
setPosition(v);
}
}
}<file_sep>-- lua script to load in values for the Rifle
name = "<NAME>";
damage = 60;
range = 200;
accuracy = 0;
recoilUp = 1;
recoilDown = 1;
clipSize = 12;
rateOfFire = 1;
reloadSpeed = 1;
projectilesPerShot = 1;
-- Projectile Info
lifespan = 4;
speed = 1200;
dropOff = 0;
destroyOnImpact = true;
bounceLoss = 1;
AOE = false;
explodes = false;
automatic = false;<file_sep>#ifndef SCREENMANAGER_H
#define SCREENMANAGER_H
#include "Screen.h"
#include "TitleScreen.h"
#include "GameScreen.h"
namespace Screen
{
class ScreenManager
{
public:
//Screen Manager is a singleton class
static ScreenManager& getInstance()
{
static ScreenManager instance;
return instance;
}
void Initialize(Screen* nextScreen);
void LoadScreen(Screen* nextScreen);
void UnloadScreen();
void Update();
void Draw(System::Window &window);
Screen* currentScreen;
private:
ScreenManager() {};
ScreenManager(ScreenManager const&);
void operator=(ScreenManager const&);
};
static ScreenManager& getScreenManager()
{
return ScreenManager::getInstance();
}
}
#endif<file_sep>#include "Nuke.h"
#include "EntityManager.h"
#include "../Map/Map.h"
#include "../Screen/EndScreen.h"
#include "../Screen/GameScreen.h"
#include <stdio.h>
Entity::Nuke::Nuke(float centerX)
:Entity(centerX -450, 0, 900, Map::getMap().getPixelHeight()),
image("nuke.png"),
sound("nuke.wav")
{
col = new Collision::AABBCollider(body, this);
timeOfDeath = System::Time::getInstance().time() + 1.4;
ghost = true;
sound.Play();
}
void Entity::Nuke::update()
{
if(timeOfDeath <= System::Time::getInstance().time())
{
removeThis();
if(getEntityManager().getRed() && getEntityManager().getBlue())
{
Screen::getScreenManager().LoadScreen(new Screen::GameScreen());
}
else
{
Screen::getScreenManager().LoadScreen(new Screen::EndScreen());
}
}
else
{
if(EntityManager::getInstance().getBlue() != NULL && EntityManager::getInstance().getBlue()->getBody().overlaps(getBody()))
EntityManager::getInstance().getBlue()->removeThis();
if(EntityManager::getInstance().getRed() != NULL && EntityManager::getInstance().getRed()->getBody().overlaps(getBody()))
EntityManager::getInstance().getRed()->removeThis();
}
}
void Entity::Nuke::draw(System::Window& window)
{
window.drawImage(image, getPosition(), 4, 4);
}<file_sep>#ifndef WINDOW_H
#define WINDOW_H
#include "Keyboard.h"
#include "Mouse.h"
#include "../Graphics/Sprite.h"
#include <SFML/Graphics.hpp>
#include <SFML/System/Vector2.hpp>
#include <string>
#include <stdlib.h>
#include "../Utility/Rect.h"
namespace System
{
class Window
{
sf::RenderWindow window;
Keyboard keyboard;
Mouse mouse;
float globalXScale;
float globalYScale;
Window()
:window(sf::VideoMode(100, 100), "Game")
{
};
Window(Window const&);
void operator=(Window const&);
public:
static Window& getInstance()
{
static Window instance;
return instance;
}
void initialize(unsigned int width, unsigned int height, std::string name);
unsigned int GetWidth() const;
unsigned int GetHeight() const;
bool drawText(Vector2f position, std::string text, int size = 12, std::string font = "arial.ttf");
bool drawText(float posX, float posY, std::string text, int size = 12, std::string font = "arial.ttf");
bool drawRect(Rect rect);
bool drawRect(float posX, float posY, float width, float height);
bool drawSprite(Graphics::Sprite sprite, Vector2f position, int frame);
bool drawImage(Graphics::Image image, Vector2f position, float scaleX = 1.0, float scaleY = 1.0, float degrees = 0);
void clear();
void display();
bool isOpen();
void update();
void close();
Keyboard& getKeyboard();
Mouse& getMouse();
void initializeFullScreen(unsigned int width, unsigned int height, std::string name);
};
static Window& getWindow()
{
return Window::getInstance();
}
static Keyboard& getKeyboard()
{
return Window::getInstance().getKeyboard();
}
static Mouse& getMouse()
{
return Window::getInstance().getMouse();
}
}
#endif
<file_sep>#pragma once
#include "Vector2f.h"
float Vector2f::dot(Vector2f const& v)
{
return x * v.x + y * v.y;
}
Vector2f Vector2f::operator=(Vector2f const& v)
{
x = v.x;
y = v.y;
return *this;
}
Vector2f Vector2f::operator+=(Vector2f const& v)
{
x += v.x;
y += v.y;
return *this;
}
Vector2f Vector2f::operator-=(Vector2f const& v)
{
x -= v.x;
y -= v.y;
return *this;
}
Vector2f Vector2f::operator*=(float const& scaler)
{
x *= scaler;
y *= scaler;
return *this;
}
Vector2f Vector2f::operator+(Vector2f const& v) const
{
Vector2f vec;
vec.x = x + v.x;
vec.y = y + v.y;
return vec;
}
Vector2f Vector2f::operator-(Vector2f const& v) const
{
Vector2f vec;
vec.x = x - v.x;
vec.y = y - v.y;
return vec;
}
Vector2f Vector2f::operator*(float scaler) const
{
Vector2f vec;
vec.x = x * scaler;
vec.y = y * scaler;
return vec;
}
Vector2f Vector2f::SetValues(float x, float y)
{
this->x = x;
this->y = y;
return *this;
}
Vector2f Vector2f::flip()
{
return *this *=- 1;
}
float Vector2f::magnitude()
{
return sqrt(x*x + y*y);
}
float Vector2f::magnitudeSquared()
{
return x*x + y*y;
}
float Vector2f::length(Vector2f vec)
{
return (*this - vec).magnitude();
}
float Vector2f::lengthSquared(Vector2f vec)
{
return (*this - vec).magnitudeSquared();
}
//Rotates the Vector by angle radians
Vector2f Vector2f::rotate(float angle)
{
float x0 = x;
float y0 = y;
x = x0 * cos(angle) - y0 * sin(angle);
y = x0 * sin(angle) + y0 * cos(angle);
return *this;
}
Vector2f Vector2f::zero()
{
x = 0;
y = 0;
return *this;
}
Vector2f Vector2f::normalize()
{
float currentMagnitude = magnitude();
if(currentMagnitude)
{
*this *= 1.0f / currentMagnitude;
}
return *this;
}
Vector2f Vector2f::clamp(float maxSpeed)
{
float currentMagnitude = magnitude();
if(currentMagnitude && (currentMagnitude > maxSpeed))
{
*this *= maxSpeed / currentMagnitude;
}
return *this;
}
Vector2f Vector2f::clampX(float maxSpeed)
{
float currentMagnitude = abs(x);
if(currentMagnitude && (currentMagnitude > maxSpeed))
{
x *= maxSpeed / x;
}
return *this;
}
Vector2f Vector2f::clampY(float maxSpeed)
{
float currentMagnitude = abs(y);
if(currentMagnitude && (currentMagnitude > maxSpeed))
{
y *= maxSpeed / y;
}
return *this;
}<file_sep>#include "Screen.h"
Screen::Screen::Screen(void)
{
}
Screen::Screen::~Screen(void)
{
}
void Screen::Screen::LoadScreen(){
}
void Screen::Screen::UnloadScreen(){
}
void Screen::Screen::Update(){
}
void Screen::Screen::Draw(System::Window& window)
{
}<file_sep>#pragma once
#include "Goal.h"
#include <stack>
namespace AI
{
template <class EntityClass>
class CompositeGoal : public Goal<EntityClass>
{
protected:
std::stack<Goal<EntityClass>*> subGoals;
GoalStatus statusOfSubgoals;
void terminateSubgoals();
GoalStatus processSubgoals();
public:
CompositeGoal(EntityClass* owner);
// remove all of the subgoals
void removeAllSubgoals();
// add a subgoal to the front of the subgoals
void addSubgoal( Goal<EntityClass>* goal );
// Process goals
GoalStatus process();
// Terminate the function
void terminate();
virtual ~CompositeGoal();
};
}<file_sep>#include "Image.h"
#include <SFML/Graphics/Image.hpp>
Graphics::Image::Image() {
img.create(100, 100);
}
Graphics::Image::Image(const std::string& filename) {
img.loadFromFile(filename);
}
void Graphics::Image::create(int width, int height) {
img.create(width, height);
}
void Graphics::Image::create(int width, int height, const Color& color = Color()) {
sf::Color col(color.r, color.g, color.b, color.a);
sf::Image im;
im.create(width, height, col);
img.loadFromImage(im);
}
void Graphics::Image::create(int width, int height, const unsigned char* pixels) {
sf::Image im;
im.create(width, height, pixels);
img.loadFromImage(im);
}
bool Graphics::Image::loadFromFile(const std::string& filename) {
return img.loadFromFile(filename);
}
bool Graphics::Image::loadFromMemory(const void* data, std::size_t size) {
return img.loadFromMemory(data, size);
}
bool Graphics::Image::saveToFile(const std::string name) const {
sf::Image save = img.copyToImage();
return save.saveToFile(name);
}
int Graphics::Image::getWidth() const {
return img.getSize().x;
}
int Graphics::Image::getHeight() const {
return img.getSize().y;
}
void Graphics::Image::setPixel(int x, int y, const Color& color) {
sf::Color col(color.r, color.g, color.b, color.a);
sf::Image set = img.copyToImage();
set.setPixel(x, y, col);
img.update(set);
}
Graphics::Color Graphics::Image::getPixel(int x, int y) const {
sf::Image pix = img.copyToImage();
sf::Color color = pix.getPixel(x, y);
return Color(color.r, color.g, color.b, color.a);
}
const unsigned char* Graphics::Image::getPixelsPtr() const {
sf::Image pix = img.copyToImage();
return pix.getPixelsPtr();
}
void Graphics::Image::setSmooth(bool smooth) {
img.setSmooth(smooth);
}
bool Graphics::Image::isSmooth() {
return img.isSmooth();
}
void Graphics::Image::setRepeated(bool repeat) {
img.setRepeated(repeat);
}
bool Graphics::Image::isRepeated() {
return img.isRepeated();
}
<file_sep>#ifndef TITLESCREEN_H
#define TITLESCREEN_H
#include "Screen.h"
#include "ScreenManager.h"
namespace Screen
{
class TitleScreen:public Screen
{
public:
TitleScreen(void);
~TitleScreen(void);
void LoadScreen();
void UnloadScreen();
void Update();
void Draw(System::Window &window);
};
}
#endif<file_sep>#include "CompositeGoal.h"
template <class EntityClass>
void AI::CompositeGoal<EntityClass>::terminateSubgoals()
{
if( subGoals.size() == 0 && subGoals.top()->isActive() )
{
subGoals.top()->terminate();
}
}
template <class EntityClass>
AI::GoalStatus AI::CompositeGoal<EntityClass>::processSubgoals()
{
while( subGoals.size() != 0 &&
(subGoals.top()->isComplete() || subGoals.top()->hasFailed()) )
{
subGoals.top()->terminate();
subGoals.pop();
}
if( subGoals.size() != 0 )
{
statusOfSubgoals = subGoals.top()->process();
if( statusOfSubgoals == completed && subGoals.size() > 1 )
{
return active;
}
else
{
return statusOfSubgoals;
}
}
else
{
return completed;
}
}
template <class EntityClass>
AI::CompositeGoal<EntityClass>::CompositeGoal(EntityClass* owner)
: Goal(owner),
statusOfSubgoals(inactive)
{
}
// remove all of the subgoals
template <class EntityClass>
void AI::CompositeGoal<EntityClass>::removeAllSubgoals()
{
subGoals.top()->terminate();
while(!subGoals.empty())
{
delete subGoals.top();
subGoals.pop();
}
}
// add a subgoal to the front of the subgoals
template <class EntityClass>
void AI::CompositeGoal<EntityClass>::addSubgoal( Goal<EntityClass>* goal )
{
subGoals.push( goal );
}
// Process goals
template <class EntityClass>
AI::GoalStatus AI::CompositeGoal<EntityClass>::process()
{
activateIfInactive();
status = processSubgoals();
return status;
}
// Terminate the function
template <class EntityClass>
void AI::CompositeGoal<EntityClass>::terminate()
{
terminateSubgoals();
}
template <class EntityClass>
AI::CompositeGoal<EntityClass>::~CompositeGoal()
{
while(!subGoals.empty())
{
delete subGoals.top();
subGoals.pop();
}
}<file_sep>-- lua script to load in values for the ThowingKnifeShotgun
name = "<NAME>";
damage = 7;
range = 200;
accuracy = 1.04719755;
recoilUp = 1;
recoilDown = 1;
clipSize = 12;
rateOfFire = 2;
reloadSpeed = 1;
projectilesPerShot = 5;
-- Projectile Info
lifespan = 5;
speed = 500;
dropOff = 100;
destroyOnImpact = true;
bounceLoss = 1;
AOE = false;
explodes = false;
automatic = false;<file_sep>#pragma once
/**
* Sprite class based on source from LaurentGomila
* https://github.com/LaurentGomila/SFML/wiki/Source:-AnimatedSprite
*/
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/Texture.hpp>
#include "../Utility/Vector2f.h"
#include "../Utility/Rect.h"
#include "Image.h"
#ifndef WINDOW_H
namespace System
{
class Window;
}
#endif
namespace Graphics
{
class Sprite
{
public:
Sprite();
void setSpriteSheet(Image& imgSheet);
void setSpriteSheet(const std::string& sheetName);
void addFrame(const Vector2f& startLoc, const Vector2f& offset);
void addFrame(const Rect& rec);
void addFrames(const Vector2f& offset);
void addFrames(int width, int height);
std::size_t getSize() const;
Rect getFrame(int index) {return frames[index];}
Image* getSheet() { return tex; }
Rect getFrameRect(int index) { return frames[index]; }
private:
std::vector<Rect> frames;
Image* tex;
friend class System::Window;
};
}
<file_sep>#include "Keyboard.h"
System::Keyboard::Keyboard()
{
for(int i = 0; i < Key::KeyCount; i++)
{
keys[i] = Key::ksUp;
}
}
void System::Keyboard::update()
{
for(int i = 0; i < Key::KeyCount; i++)
{
if(keys[i] == Key::ksLetGo)
keys[i] = Key::ksUp;
else if(keys[i] == Key::ksHit)
keys[i] = Key::ksHeld;
}
}
void System::Keyboard::onKeyPress(sf::Keyboard::Key key)
{
keys[key] = Key::ksHit;
}
void System::Keyboard::onKeyRelease(sf::Keyboard::Key key)
{
keys[key] = Key::ksLetGo;
}
bool System::Keyboard::keyHit(Key::Key key)
{
return keys[key] == Key::ksHit;
}
bool System::Keyboard::keyHeld(Key::Key key)
{
return keys[key] == Key::ksHit || keys[key] == Key::ksHeld;
}
bool System::Keyboard::keyLetGo(Key::Key key)
{
return keys[key] == Key::ksLetGo;
}
bool System::Keyboard::keyUp(Key::Key key)
{
return keys[key] == Key::ksUp || keys[key] == Key::ksLetGo;
}
bool System::Keyboard::anyKeyHeld()
{
for(int i = 0; i < Key::KeyCount; i++)
{
if(keyHeld((Key::Key) i))
return true;
}
return false;
}
bool System::Keyboard::anyKeyHit()
{
for(int i = 0; i < Key::KeyCount; i++)
{
if(keyHit((Key::Key) i))
return true;
}
return false;
}<file_sep>#pragma once
#include "Entity.h"
#include "../Collision/AABBCollider.h"
#include "../System/Time.h"
#include "../Graphics/Image.h"
#include "../Audio/Sound.h"
namespace Entity
{
class Nuke : public Entity
{
Graphics::Image image;
float timeOfDeath;
Audio::Sound sound;
public:
Nuke(float centerX);
void update();
void draw(System::Window&);
};
}<file_sep>#include "AABBCollider.h"
Collision::AABBCollider::AABBCollider(Rect& body, Entity::Entity* p)
:Collider(body.getTopLeft(), p),
box(body)
{
type = AABB;
clearCollisionData();
}
void Collision::AABBCollider::collide(Collider* col)
{
switch(col->getType())
{
case None:
box.containsPoint(col->getPosition());
break;
case AABB:
AABBCollision(dynamic_cast<AABBCollider*>(col));
}
}
Collision::Type Collision::AABBCollider::getType()
{
return type;
}
Vector2f Collision::AABBCollider::getPosition()
{
return position;
}
Rect Collision::AABBCollider::getBody()
{
return box;
}
void Collision::AABBCollider::AABBCollision(AABBCollider* col)
{
float velX = 0;
float velY = 0;
float velX2 = 0;
float velY2 = 0;
if(parent != NULL)
{
velX = parent->getVelocity().x;
velY = parent->getVelocity().y;
}
if(col->parent != NULL)
{
velX2 = col->parent->getVelocity().x;
velY2 = col->parent->getVelocity().y;
}
float bottom1 = box.getBottom();
float bottom2 = col->box.getBottom();
float top1 = box.getTop();
float top2 = col->box.getTop();
float left1 = box.getLeft();
float left2 = col->box.getLeft();
float right1 = box.getRight();
float right2 = col->box.getRight();
if ((bottom1 + 1 + velY> top2 + velY2) &&
(top1 + velY < bottom2 + velY2) &&
(right1 + velX > left2 + velX2) &&
(left1 + velX < right2 + velX2) &&
bottom1 <= top2)
{
if (velY >= 0)
{
if(parent != NULL)
parent->onCollideDown(col->parent);
if(col->parent != NULL)
col->parent->onCollideDown(parent);
box.setBottom(top2);
collideDown = true;
col->collideUp = true;
}
}
if ((bottom1 + velY > top2 + velY2) &&
(top1 - 1 + velY < bottom2 + velY2) &&
(right1 + velX > left2 + velX2) &&
(left1 + velX < right2 + velX2) &&
top1 >= bottom2)
{
if (velY <= 0)
{
if(parent != NULL)
parent->onCollideUp(col->parent);
if(col->parent != NULL)
col->parent->onCollideUp(parent);
box.setTop(bottom2);
collideUp = true;
col->collideDown = true;
}
}
if ((bottom1 + velY > top2 + velY2) &&
(top1 + velY < bottom2 + velY2) &&
(right1 + 1 + velX > left2 + velX2) &&
(left1 + velX < right2) + velX2 &&
right1 <= left2)
{
if (velX >= 0)
{
if(parent != NULL)
parent->onCollideRight(col->parent);
if(col->parent != NULL)
col->parent->onCollideLeft(parent);
box.setRight(left2);
collideRight = true;
col->collideLeft = true;
}
}
if ((bottom1 + velY > top2 + velY2) &&
(top1 + velY < bottom2 + velY2) &&
(right1 + velX > left2 + velX2) &&
(left1 - 1 + velX < right2 + velX2) &&
left1 >= right2)
{
if (velX <= 0)
{
if(parent != NULL)
parent->onCollideLeft(col->parent);
if(col->parent != NULL)
col->parent->onCollideRight(parent);
box.setLeft(right2);
collideLeft = true;
col->collideRight = true;
}
}
}
void Collision::AABBCollider::clearCollisionData()
{
collideRight = false;
collideLeft = false;
collideDown = false;
collideUp = false;
}
bool Collision::AABBCollider::getCollideRight()
{
return collideRight;
}
bool Collision::AABBCollider::getCollideLeft()
{
return collideLeft;
}
bool Collision::AABBCollider::getCollideDown()
{
return collideDown;
}
bool Collision::AABBCollider::getCollideUp()
{
return collideUp;
}<file_sep>-- lua script to load in values for the Rifle
name = "<NAME>";
damage = 10;
range = 200;
accuracy = 0.34906585;
recoilUp = 1;
recoilDown = 1;
clipSize = 12;
rateOfFire = 8;
reloadSpeed = 1;
projectilesPerShot = 1;
-- Projectile Info
lifespan = 3;
speed = 800;
dropOff = 0;
destroyOnImpact = false;
bounceLoss = 1;
AOE = false;
explodes = false;
automatic = true;<file_sep>#include "Rect.h"
Rect::Rect()
:position(0, 0),
width(0),
height(0)
{
}
Rect::Rect(Vector2f topLeftPos, float rectWidth, float rectHeight)
:position(topLeftPos),
width(rectWidth),
height(rectHeight)
{
}
Rect::Rect(float left, float top, float rectWidth, float rectHeight)
:position(left, top),
width(rectWidth),
height(rectHeight)
{
}
Vector2f Rect::getTopLeft() const
{
return position;
}
float Rect::getHeight() const
{
return height;
}
float Rect::getWidth() const
{
return width;
}
float Rect::getTop() const
{
return position.y;
}
float Rect::getBottom() const
{
return position.y + height;
}
float Rect::getLeft() const
{
return position.x;
}
float Rect::getRight() const
{
return position.x + width;
}
void Rect::setTopLeft(Vector2f topLeft)
{
position = topLeft;
}
void Rect::setHeight(float rectHeight)
{
height = rectHeight;
}
void Rect::setWidth(float rectWidth)
{
width = rectWidth;
}
Vector2f Rect::getCenter() const
{
return position + Vector2f(width/2, height/2);
}
Vector2f Rect::setCenter(Vector2f const& center)
{
position = center - Vector2f(width/2, height/2);
return center;
}
bool Rect::containsPoint(Vector2f)
{
return false;
}
bool Rect::overlaps(Rect const& otherRect)
{
if ((getBottom() > otherRect.getTop()) &&
(getTop() < otherRect.getBottom()) &&
(getRight() > otherRect.getLeft()) &&
(getLeft() < otherRect.getRight()))
{
// The two objects' collision boxes overlap
return true;
}
// The two objects' collision boxes do not overlap
return false;
}
Vector2f Rect::getBottomRight() const
{
return Vector2f(position.x + width, position.y + height);
}
Vector2f Rect::setBottomRight(Vector2f const& bottomRight)
{
position = Vector2f(bottomRight.x - width, bottomRight.y - height);
return bottomRight;
}
Rect Rect::operator=(Rect const& other)
{
position = other.position;
width = other.width;
height = other.height;
return *this;
}
float Rect::setTop(float top)
{
position.y = top;
return top;
}
float Rect::setBottom(float bottom)
{
position.y = bottom - height;
return bottom;
}
float Rect::setLeft(float left)
{
position.x = left;
return left;
}
float Rect::setRight(float right)
{
position.x = right - width;
return right;
}<file_sep>#pragma once
#define MIN_COLOR 0
#define MAX_COLOR 255
namespace Graphics
{
class Color {
public:
Color();
Color(int red, int green, int blue, int alpha);
bool operator ==(const Color& right);
bool operator !=(const Color& right);
Color operator +(const Color& right);
Color operator *(const Color& right);
Color& operator +=(const Color& right);
Color& operator *=(const Color& right);
int r, g, b, a;
static const Color Black;
static const Color White;
static const Color Red;
static const Color Green;
static const Color Blue;
static const Color Yellow;
static const Color Magenta;
static const Color Cyan;
static const Color Transparent;
private:
int clamp(int value);
};
}<file_sep>#ifndef SOUND_H
#define SOUND_H
#include "SFML\Audio.hpp"
namespace Audio
{
class Sound
{
public:
Sound(std::string file_name);
~Sound(void);
void Play();
void Pause();
void Stop();
void setLooping(bool loops);
bool getLooping();
void setPitch(float new_pitch);
float getPitch();
void setVolume(float new_volume);
float getVolume();
void setPlayingOffset(float new_offset);
float getPlayingOffset();
bool isPlaying() {return sound.getStatus() == sf::Sound::Playing;}
float getDuration();
private:
sf::Sound sound;
sf::SoundBuffer buffer;
float volume;
float pitch;
float length;
float offset;
bool looping;
bool playing;
};
}
#endif<file_sep>#pragma once
#include <vector>
#include "../System/Window.h"
#include "Entity.h"
#include "Player.h"
namespace Entity
{
class EntityManager
{
private:
std::vector<Entity*> entities;
Player* red;
Player* blue;
public:
//Entity Manager is a singleton class
static EntityManager& getInstance()
{
static EntityManager instance;
return instance;
}
void clear();
void update();
void add(Entity*);
void draw(System::Window& window);
Player* getRed();
Player* getBlue();
private:
EntityManager() {};
EntityManager(EntityManager const&);
void operator=(EntityManager const&);
void collide();
void cull();
};
static EntityManager& getEntityManager()
{
return EntityManager::getInstance();
}
}<file_sep>#ifndef GAMESCREEN_H
#define GAMESCREEN_H
#include "Screen.h"
#include "../Entity/EntityManager.h"
#include "ScreenManager.h"
namespace Screen
{
class GameScreen:public Screen
{
public:
GameScreen(void);
~GameScreen(void);
void LoadScreen();
void UnloadScreen();
void Update();
void Draw(System::Window &window);
};
}
#endif<file_sep>#include "randf.h"
float randf()
{
return ((float) rand()) / RAND_MAX;
}
float randf(float max)
{
if(max == 0)
max = .000001;
return ((float) rand()) / (RAND_MAX / max);
}
float randf(float min, float max)
{
if(max - min == 0)
max += .000001;
return min + ((float) rand()) / (RAND_MAX / (max - min));
}<file_sep>#include "Sprite.h"
Graphics::Sprite::Sprite()
{
}
void Graphics::Sprite::setSpriteSheet(Image& imgSheet) {
tex = &imgSheet;
}
void Graphics::Sprite::setSpriteSheet(const std::string& sheetName) {
tex = new Image(sheetName);
}
void Graphics::Sprite::addFrame(const Vector2f& startLoc, const Vector2f& offset) {
frames.push_back(Rect(startLoc.x, startLoc.y, offset.x, offset.y));
}
void Graphics::Sprite::addFrame(const Rect& rec) {
frames.push_back(rec);
}
void Graphics::Sprite::addFrames(const Vector2f& offset) {
addFrames((int)offset.x, (int)offset.y);
}
void Graphics::Sprite::addFrames(int width, int height) {
int w = tex->getWidth(), h = tex->getHeight();
for(int y = 0; y < h; y += height) {
for(int x = 0; x < w; x += width) {
frames.push_back(Rect(x, y, width, height));
}
}
}
std::size_t Graphics::Sprite::getSize() const {
return frames.size();
}
<file_sep>-- lua script to load in values for the Rifle
name = "Damage";
damage = 1;
speed = 1;
damgeResistance = 1;
timeScale = .2;
duration = 2;
permanent = false;<file_sep>#include "ScreenManager.h"
void Screen::ScreenManager::Initialize(Screen* nextScreen){
currentScreen = nextScreen;
currentScreen->LoadScreen();
}
void Screen::ScreenManager::LoadScreen(Screen* nextScreen){
currentScreen->UnloadScreen();
delete currentScreen;
currentScreen = nextScreen;
currentScreen->LoadScreen();
}
void Screen::ScreenManager::UnloadScreen(){
currentScreen->UnloadScreen();
}
void Screen::ScreenManager::Update(){
currentScreen->Update();
}
void Screen::ScreenManager::Draw(System::Window &window){
currentScreen->Draw(window);
}<file_sep>#include "Goal.h"
template <class EntityClass>
AI::Goal<EntityClass>::Goal(EntityClass* owner)
{
owner = owner;
status = inactive;
}
// activates the goal
template <class EntityClass>
void AI::Goal<EntityClass>::activate()
{
status = active;
}
// processes the goal
template <class EntityClass>
AI::GoalStatus AI::Goal<EntityClass>::process()
{
return status;
}
// terminates the goal's processes
template <class EntityClass>
void AI::Goal<EntityClass>::terminate()
{
}
// returns true if the goal is completed
template <class EntityClass>
bool AI::Goal<EntityClass>::isComplete() const
{
return status == completed;
}
// returns true if the goal is active
template <class EntityClass>
bool AI::Goal<EntityClass>::isActive() const
{
return status == active;
}
// returns true if the goal is inactive
template <class EntityClass>
bool AI::Goal<EntityClass>::isInactive() const
{
return status == inactive;
}
// returns true if the goal has failed
template <class EntityClass>
bool AI::Goal<EntityClass>::hasFailed() const
{
return status == failed;
}
// if the goal is inactive, the goal gets activated
template <class EntityClass>
void AI::Goal<EntityClass>::activateIfInactive()
{
if( status == inactive )
{
activate();
}
}
// if the goal has failed, reactive it
template <class EntityClass>
void AI::Goal<EntityClass>::reactivateIfFailed()
{
if( hasFailed() )
{
status = inactive;
}
}<file_sep>#pragma once
#include "Vector2f.h"
class Rect
{
Vector2f position;
float width;
float height;
public:
Rect();
Rect(Vector2f, float, float);
Rect(float, float, float, float);
Rect operator=(Rect const&);
Vector2f getTopLeft() const;
Vector2f getBottomRight() const;
Vector2f getCenter() const;
float getHeight() const;
float getWidth() const;
void setTopLeft(Vector2f);
Vector2f setBottomRight(Vector2f const&);
Vector2f setCenter(Vector2f const&);
void setHeight(float);
void setWidth(float);
float getTop() const;
float getBottom() const;
float getLeft() const;
float getRight() const;
float setTop(float);
float setBottom(float);
float setLeft(float);
float setRight(float);
bool containsPoint(Vector2f);
bool overlaps(Rect const&);
};
|
b0c4e9f3648c5a1c1ffd76503ab61e5de37dc6bf
|
[
"Markdown",
"C",
"C++",
"Lua"
] | 60
|
C++
|
dennis-ehrhardt/AtomicDuckLord
|
e38828e9f84506a66fda5059aeb0da07b1ea8f06
|
3a25e16de3adc98c14a5728cb98773a17dd82e0c
|
refs/heads/master
|
<file_sep>
# Deciphering the morphology of motor evoked potentials
## Description
This repo contains the code required to reproduce the results outlined in the paper **Deciphering the morphology of motor evoked potentials**.
## How to use
### Installation
Clone this repository
```bash
git clone https://github.com/JanYperman/morphology.git
```
Install [Anaconda](https://www.anaconda.com/distribution/) (or miniconda) and create a new environment called _morphology_ and activate it.
```bash
conda create --name morphology python=3 pandas scikit-learn pyyaml scipy matplotlib
conda activate morphology
```
### Running the pipeline
To reproduce our results, run:
```python
python frontiers_code.py
```
This will run the complete pipeline using the settings as they were in outlined in the manuscript. All the tables and figures which are based on the small dataset (which holds no sensitive data) will be generated and written to _table\_#.txt_ and _fig#\_description.pdf_ files. Note that the tables are in latex-format.
The settings for the pipeline can be changed, either by changing them directly in [config.yaml](../master/config.yaml), or by passing them as command line arguments. A few examples:
```bash
# List all possible commandline arguments
python frontiers_code.py --help
# Run the pipeline using the feature with id 400
python frontiers_code.py -chosen_feature 400
# Run the pipeline, skipping the cross-validation step
python frontiers_code.py --skip_first_phase
# Reproduce the results for different filters (supplementary)
python generate_supplementary.py
```
## Dataset
The dataset [dataset.zip](../master/dataset.zip) contains the data required to reproduce the main results. The main file, __dataset.csv__ contains the following fields:
* __name:__ Identifier for the neurologist who annotated the time series
* __visitid:__ Unique identifier for the visit
* __anatomy\_side:__ String indicating the anatomy (AH or APB) and the side on which the measurement was performed (L or R)
* __morph:__ The label assigned by the neurologist (1=normal, 2=abnormal, 3=bad data)
* __clinic\_id__: Unique identifier for a patient, which is used to ensure no patients end up in both the train and the test set.
* __timeseries\_id:__ An identifier to link to the timeseries associated with this entry. E.g. if this is 123 then the timeseries may be found in _timeseries/123.txt_. The corresponding features would then be found in _features/123.txt_.
* __computer:__ This field indicates the machine on which the measurement was performed. There are two machines, one labeled 'new', the other is labeled 'old'.
The two folders _timeseries_ and _features_ contain the individual timeseries and features respectively. They may be coupled to the entries in __dataset.csv__ by means of the _timeseries\_id_ field. Note that this is done automatically when running [frontiers_code.py](../master/frontiers_code.py), which stores a pickled dataframe called _frontiers\_dataset.p_ in the root.
### Calculate approximate entropy
To calculate the approximate entropy for new timeseries, use the function `normalized_approximate_entropy` defined in `calculate_apen.py`. It will assume 1920 samples per timeseries.This function also applies the normalization with the same parameters as those used in the paper. The function is illustrated by recalculating the approximate entropy of the timeseries in the dataset.
<file_sep>"""Morphology data analysis pipeline
This code can be used to reproduce the results reported in the paper
"Deciphering the morphology of motor evoked potentials".
Example:
To run the code using the default parameters, as they were used in
the paper, run::
$ python frontiers_code.py
"""
import argparse
import functools
import multiprocessing
import os
import pickle
import re
import string
import zipfile
import tqdm
import matplotlib.pyplot as plt
params = {
'font.size' : 12,
}
plt.rcParams.update(params)
from matplotlib.lines import Line2D
from matplotlib.offsetbox import AnchoredText
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (accuracy_score, average_precision_score,
cohen_kappa_score, confusion_matrix, f1_score,
precision_recall_curve, precision_score,
recall_score, roc_auc_score, roc_curve)
from sklearn.model_selection import GroupKFold, ShuffleSplit, GroupShuffleSplit
from sklearn.neighbors import KernelDensity
from sklearn.exceptions import UndefinedMetricWarning
from scipy.signal import find_peaks
from scipy.stats import iqr
import calculate_apen as ca
import yaml
CUTOFF = 70
from scipy.signal import butter, lfilter, freqz
def combine_av_std(df):
major_columns = list(set([h for h in df.keys()]))
df.columns = [' '.join(col).strip() for col in df.columns.values]
fmt = '%.2f (%.2f)'
for mc in major_columns:
pass
def normalize(x):
median = np.median(x)
print('median: %.10f' % median)
iqr = scipy.stats.iqr(x)
print('iqr: %.10f' % iqr)
return 1. / (1 + np.exp(-(x - median)/(iqr / 1.35)))
def min_max(x, minimum=None, maximum=None):
if minimum is None:
print('min: %.10f' % np.min(x))
print('max: %.10f' % np.max(x))
return (x - np.min(x)) / (np.max(x) - np.min(x))
else:
return (x - minimum) / (maximum - minimum)
def calc_apen(indrow, filt=False, norm=True):
_, row = indrow
ts = row.timeseries
if len(ts) != 1920:
ts = resample(ts, 1920)
# Visualize filter
# fig, ax = plt.subplots(1)
# ax.plot(ts)
if filt:
ts = butter_highpass_filter(ts, cutoff=100, fs=19200, order=1)
# ax.plot(ts)
# plt.show()
if norm:
apen = ca.normalized_approximate_entropy(ts, 2, 0.2)
else:
apen = ca.approximate_entropy(ts, 2, 0.2)
return apen
def butter_highpass(cutoff, fs, order=1):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
try:
b, a = butter(order, normal_cutoff, btype='high', analog=False)
except:
print(butter(order, normal_cutoff, btype='high', analog=False))
# b, a = butter(order, normal_cutoff, btype='high', analog=False, output='sos'),
# w, h = freqz(b, a, worN=2000),
# plt.plot((fs * 0.5 / np.pi) * w, abs(h), label=\"order = %d\" % order),
# plt.show(),
return b, a
def butter_highpass_filter(data, cutoff, fs, order=1):
b, a = butter_highpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
def process_group(group):
'''
Process group with grouping based on having the same timeseries.
This is a helper function to reconstruct the pandas dataframe from the
zipped csv-files.
'''
cur_id = group.iloc[0].timeseries_id
with zipfile.ZipFile('dataset.zip') as z:
ts_file = 'dataset/timeseries/%03i.txt' % cur_id
feat_file = 'dataset/features/%03i.txt' % cur_id
ts = np.loadtxt(z.open(ts_file, 'r'))
feat = np.loadtxt(z.open(feat_file, 'r'))
rows = []
for _, row in group.iterrows():
tmp = row.to_dict()
tmp['timeseries'] = ts
tmp['features'] = feat
rows.append(tmp)
return rows
def create_dataframe():
'''
Recreate the dataset from the csv files
'''
with zipfile.ZipFile('dataset.zip') as z:
df = pd.read_csv(z.open('dataset/dataset.csv', 'r'))
p = multiprocessing.Pool()
groups = p.map(process_group, [g for _, g in df.groupby('timeseries_id', as_index=False)], chunksize=50)
p.close()
# Flatten list
rows = sum(groups, [])
dataset = pd.DataFrame(rows)
dataset = dataset[['name', 'visitid', 'anatomy_side', 'morph', 'clinic_id', 'timeseries_id', 'timeseries', 'features', 'computer']]
return dataset
def plot_distribution_with_samples(df_test, feat_vals, classes, neur_thresholds, df, feat_id):
"""
Plot the distributions of the chosen feature separately for the normal and abnormal class
Also display 3 samples at various points in the distribution as an illustration.
Finally, indicate the thresholds of the various neurologists on the distribution
"""
fig = plt.figure(constrained_layout=True, figsize=(7, 7))
gs = fig.add_gridspec(2, 3, height_ratios=[1, 3])
## Plot the samples
axs = [fig.add_subplot(gs[0, s]) for s in range(3)]
ids = string.ascii_uppercase
for i, (feat_val, cclass) in enumerate(zip(feat_vals, classes)):
tmp_df = df[df['vote'] == cclass].copy()
tmp_df['dist'] = np.abs(feat_val - np.vstack(tmp_df.features.values)[:, feat_id])
ts = tmp_df.sort_values(by='dist').iloc[0].timeseries[CUTOFF:]
# Minus as this is how the TS is usually shown to neurologists
axs[i].plot(-ts, color='black', label='%.2f' % feat_val)
axs[i].set_title('%.2f' % feat_val)
at = AnchoredText(ids[i],
prop=dict(size=10, weight='bold'), frameon=True,
loc=1, # Upper right
)
axs[i].add_artist(at)
axs[i].set_xticks(ticks=[])
axs[i].set_yticks(ticks=[])
## Plot the distributions
agreement_count = np.sum(df_test[neur].values, axis=-1)
agreement_mask = np.logical_or(agreement_count == 2, agreement_count == 3)
neur_errors = df_test.iloc[agreement_mask, :].apen.values
abnormal = df.query('vote == 1').apen.values
normal = df.query('vote == 0').apen.values
width = 0.05
ax = fig.add_subplot(gs[1, :])
plot_gauss(neur_errors, 'neurologist disagreement', '-.', bw=width, ax=ax)
ab_x, ab_y = plot_gauss(abnormal, 'abnormal', '--', bw=width, ax=ax)
nor_x, nor_y = plot_gauss(normal, 'normal', '-', bw=width, ax=ax)
for i, (feat_val, cclass) in enumerate(zip(feat_vals, classes)):
if cclass == 0:
x, y = min(list(zip(nor_x, nor_y)), key=lambda k: abs(k[0] - feat_val))
else:
x, y = min(list(zip(ab_x, ab_y)), key=lambda k: abs(k[0] - feat_val))
label = string.ascii_uppercase[i]
ax.annotate(label,
horizontalalignment='right',
fontsize=10,
fontweight='bold',
xy=(x, y), xycoords='data',
xytext=(x + (0.1 * (feat_val - 0.5)), y + 0.3), textcoords='data',
arrowprops=dict(arrowstyle="->", linestyle="-",
color="0.",
),
)
OFFSET_LINE = -0.2
HOR_OFFSET = -0.01
MIN_SEP = 0.01
x = [0, 1]
y = [OFFSET_LINE, OFFSET_LINE]
neur_line = Line2D(x, y, color='black')
ax.add_line(neur_line)
# Check if the thresholds are too close to one another
# If so, merge the labels for visual clarity
# WARNING: This merging does not work well for separations
# that are too large!
thresh_to_plot = {}
segs = np.digitize(neur_thresholds, np.linspace(0, 1, int(1 / (MIN_SEP / 2.)) + 1))
for val in np.unique(segs):
inds = np.where((segs >= val - 1) & (segs <= val))[0]
label = '\n'.join(['N%i' % (i+1) for i in inds])
# label = '[' + ', '.join(['N%i' % (i+1) for i in inds]) + ']'
new_thresh_value = np.average(np.array(neur_thresholds)[inds])
thresh_to_plot[label] = new_thresh_value
ax.scatter(thresh_to_plot.values(), [OFFSET_LINE] * len(thresh_to_plot.values()), marker='o', color='black')
# It is assumed that the neur_thresholds are in the same order as the 'neur'-list
for label, thresh in thresh_to_plot.items():
ax.annotate(label, horizontalalignment='center', fontsize=10,
xy=(thresh, OFFSET_LINE), xycoords='data',
xytext=(thresh, OFFSET_LINE / 2.),
textcoords='data',
)
ax.set_ylim(bottom=2*OFFSET_LINE)
ax.set_xlabel('Approximate entropy')
ax.set_ylabel('density')
# plt.tight_layout()
plt.legend()
plt.savefig('fig3_distributions.pdf', bbox_inches='tight')
# plt.show()
plt.close()
def normalize(x):
med = np.median(x)
iqr_x = iqr(x)
return 1. / (1 + np.exp(- (x - med) / (1.35 * iqr_x)))
def find_peaks_ts(df):
tmp_df = df.copy()
# Uncomment to visualize peak detection
# for ts in tmp_df['timeseries'].values:
# tmp = find_peaks(ts[100:], prominence=0.02)[0]
# plt.plot(ts[100:])
# plt.scatter(tmp, ts[100:][tmp])
# plt.show()
# print(tmp)
tmp_df['peaks_count'] = tmp_df['timeseries'].apply(lambda k: find_peaks(k[100:], prominence=0.02)[0].shape[0])
# Normalize
all_vals = tmp_df['peaks_count'].values
all_vals = normalize(all_vals)
tmp_df['peaks'] = all_vals
return tmp_df
def plot_gauss(X, label, linestyle, bw=0.05, start=0., end=1., ax=None):
kde = KernelDensity(kernel='gaussian', bandwidth=bw).fit(
X.reshape((-1, 1)))
X_plot = np.linspace(start, end, 101)[:, np.newaxis]
log_dens = kde.score_samples(X_plot)
if ax is None:
plt.plot(X_plot[:, 0], np.exp(log_dens), label=label,
linestyle=linestyle, color='black')
else:
ax.plot(X_plot[:, 0], np.exp(log_dens), label=label,
linestyle=linestyle, color='black')
return X_plot[:, 0], np.exp(log_dens)
def plot_two_curves(df, neur, thresh):
"""
Plot the precision-recall curve and the ROC-curve side-by-side
"""
fig, axs = plt.subplots(1, 2, figsize=(7, 4))
plot_curve_metric(
df=df,
neur=neur,
metric=roc_curve,
y_pred=df['logreg_prob'].values,
thresh=thresh,
flip=True,
xlabel='FPR',
ylabel='TPR',
ax=axs[0]
)
plot_curve_metric(
df=df,
neur=neur,
metric=precision_recall_curve,
y_pred=df['logreg_prob'].values,
thresh=thresh,
flip=False,
xlabel='precision',
ylabel='recall',
legend_loc=3,
ax=axs[1]
)
plt.tight_layout()
plt.savefig('fig4_curves_metrics.pdf', bbox_inches='tight')
# plt.savefig('curves_metrics.png', bbox_inches='tight', dpi=300)
# plt.show()
plt.close()
class flip_train_val(GroupKFold):
"""
This is the same as GroupKFold, though it will return 1 fold as train and
n - 1 as test set, which is the opposite of the normal case. We can do this
because we are fitting a very simple model which does not need much
data to get a decent fit. This then allows us to have a bigger test set.
"""
# Flips the train and validation indices so the validation set is the larger of the two
def split(self, X, y=None, groups=None):
return ((test, train) for train, test in super(flip_train_val, self).split(X, y, groups))
def classifier(*args, **kwargs):
"""
A convenience function, to allow changing the type of classifier quickly.
"""
return LogisticRegression(**kwargs)
def curve_metric(y_true, y_pred, metric):
"""
Somewhat hacky solution to obtain the values of some metric (e.g. ROC)
for binary labels. This results in a "curve" consisting of three or
two points. We're interested in the non-trivial point.
"""
metric_a, metric_b, _ = metric(y_true, y_pred)
if metric_a.shape[0] == 3:
metric_a = metric_a[1]
metric_b = metric_b[1]
elif metric_a.shape[0] == 2:
metric_a = metric_a[0]
metric_b = metric_b[0]
return metric_a, metric_b
def plot_curve_metric(df, neur, metric, y_pred, thresh, flip=False, xlabel=None, ylabel=None,
legend_loc=0, area_metric=None, filename=None, ax=None):
'''
Plot the curve of some metric (precision-recall or ROC in our case) along with the
performances of the neurologists (which are points on the plot)
:df: The pandas dataframe containing all the data
:neur: The list of valid neurologist identifier strings
:metric: The performance metric to use (e.g. precision-recall)
:y_pred: The predictions (continuous) of our model
:thresh: The threshold to convert continuous predictions to binary ones
:flip: Flip x- and y-axis
:xlabel: The label for the x-axis
:ylabel: The label for the y-axis
:legend_loc: Determines where the legend of the plot is placed, see matplotlib docs
:area_metric: If provided prints the value of this metric as title (e.g. AUROC)
:filename: If provided, save plot to file with this name
:ax: If provided, use this matplotlib axis to plot instead of creating a new fig.
'''
if ax is None:
_, ax = plt.subplots(1, 1)
y_test_vote = df.vote.values
loo_scores_neur = leave_one_out_score(
df, neur, functools.partial(curve_metric, metric=metric))
loo_scores_log = leave_one_out_score(
df, neur, functools.partial(curve_metric, metric=metric), y_pred_ext=y_pred > thresh)
if flip:
metric_a, metric_b, _ = metric(y_test_vote, y_pred)
else:
metric_b, metric_a, _ = metric(y_test_vote, y_pred)
ax.plot(metric_a, metric_b, color='black', label='5-vote based model')
vals_neur = np.vstack(list(loo_scores_neur.values()))
vals_log = np.vstack(list(loo_scores_log.values()))
if flip:
first, second = (0, 1)
else:
first, second = (1, 0)
ax.plot(vals_neur[:, first], vals_neur[:, second],
label='neurologists 3-vote', marker='x', linestyle='', color='black')
ax.plot(vals_log[:, first], vals_log[:, second],
label='model 3-vote', marker='^', linestyle='', color='black')
if xlabel is not None:
ax.set_xlabel(xlabel)
if ylabel is not None:
ax.set_ylabel(ylabel)
if area_metric is not None:
plt.title('%.2f' % area_metric(y_test_vote, y_pred))
ax.legend(loc=legend_loc)
if filename is not None:
plt.savefig(filename, bbox_inches='tight')
def fit_and_score_fold(X_fold_train, y_fold_train, X_fold_test, y_fold_test):
"""
Fit the model using a single feature, for a specific neurologist, and
return the auc score. This will be run in parallel
"""
clf = classifier(class_weight='balanced', n_jobs=1, solver='liblinear')
clf.fit(X_fold_train, y_fold_train)
y_pred = clf.predict_proba(X_fold_test)
return roc_auc_score(y_fold_test, y_pred[:, 1])
# return average_precision_score(y_fold_test, y_pred[:, 1])
def agreement_fraction(labels_a, labels_b):
"""
Calculate the fraction of labels on which two sets agree
"""
return np.sum(labels_a == labels_b) / labels_a.shape[0]
def agreement_mat(df, n_neur, func, include_average=False):
"""
Returns a matrix containing all pairs of neurologists and
the corresponding score of agreement, based on the passed function
e.g. the Cohen kappa score
"""
mat_morph = (df
.sort_values(by=['visitid', 'anatomy_side', 'name'])
.morph
.values
.reshape((-1, n_neur)))
mat = np.zeros((n_neur, n_neur))
for i in range(n_neur):
for j in range(n_neur):
mat[i, j] = func(mat_morph[:, i], mat_morph[:, j])
if include_average:
average = (np.average(mat, axis=0).reshape((-1, 1)) * mat.shape[0] - 1.) / (mat.shape[0] - 1)
mat = np.hstack([mat, average])
return mat
def get_intrarater(df, func):
"""
Get the intrarater score, i.e., the agreement of a rater with him/her/itself
"""
intra_dict = {}
n_neur = 2
for neur, group in df.groupby('name'):
group = group.groupby(['visitid', 'anatomy_side']
).filter(lambda x: len(x) == 2)
mat = agreement_mat(group, n_neur, func)
intra_dict[neur] = mat[0, 1]
return intra_dict
def get_agreement(df, func, intra=None):
"""
Get the agreement matrix (see agreement_mat) and set the intra-rater
to the diagonal (as these have the rather uninformative perfect score
for each of the neurologist). Create a pandas dataframe from it,
so it may be easily converted to a LaTex table.
"""
neur = sorted(df.name.unique())
n_neur = df.name.nunique()
mat = agreement_mat(df, n_neur, func, include_average=True)
if intra is not None:
for key, value in intra.items():
index = neur.index(key)
mat[index, index] = value
res_df = pd.DataFrame([{name: val for name, val in zip(
neur + ['average'], row)} for row in mat], index=neur)
return res_df
def get_only_summaries(df_agree, df_cohen, intra_agree, intra_cohen, include_average=True):
"""Returns a dataframe containing only the summaries of the results
"""
summary_df = (df_agree[['average']]
.merge(df_cohen[['average']],
left_index=True,
right_index=True)
.transpose()
)
summary_df = summary_df.rename({'average_x': 'Agreement fraction', 'average_y': 'Cohen\'s kappa'}, axis=0)
summary_df['Average'] = np.average(summary_df.values, axis=1)
# Convert to format %.2f (%.2f) for inter- and intrarater
intra_agree['Average'] = np.average(list(intra_agree.values()))
intra_cohen['Average'] = np.average(list(intra_cohen.values()))
summary_dict = summary_df.to_dict()
for name, row in summary_dict.items():
for key, vals in row.items():
summary_dict[name][key] = '%.2f (%.2f)' % (summary_dict[name][key], intra_agree[name]
if 'agree' in key.lower()
else intra_cohen[name])
new_summary_df = pd.DataFrame(summary_dict)
return new_summary_df.transpose()
# for index, row in summary_df.iterrows():
# summary_df.loc[index, 'str_perf'] =
# summary_df['str_perf'] =
def leave_one_out_score(df, neur, metric, y_pred_ext=None):
"""
Create a (n-2)-vote (in our case 3) dataset for each neurologist.
We take n-2 because in our case n-1 does not always have a consensus
(e.g. 2-2 votes). If y_pred_ext is provided, we evaluate this set
of labels on each of the 3-vote sets.
"""
res_dict = {}
for name in neur:
subset = [n for n in neur if n != name]
scores = []
for subname in subset:
subsubset = [n for n in subset if n != subname]
vote = (np.average(df[subsubset].values,
axis=-1) > 0.5).astype(np.int8)
if y_pred_ext is None:
score = metric(vote, df[name].values)
else:
score = metric(vote, y_pred_ext)
scores.append(score)
res_dict[name] = np.average(scores, axis=0)
return res_dict
def print_metric_score(metric, df, neur, y_test, log_pred):
"""
Debug function to print the performance of the model according to a
given metric. Only used for confusion matrix right now.
"""
print('%s:' % metric.__name__)
print('-------------------')
# Score on the 3-vote set
perf_neur = leave_one_out_score(df, neur, metric)
for n, val in perf_neur.items():
print('%s:\t%i\t%i\n\t%i\t%i' % (n, val[0, 0], val[0, 1],
val[1, 0], val[1, 1]))
print('-------------------')
# print(perf_neur)
perf_log = leave_one_out_score(df, neur, metric, y_pred_ext=log_pred)
# print(np.average([value for value in perf_log.values()]),
# np.std([value for value in perf_log.values()]))
# Score on the 5-vote set
val = metric(y_test, y_pred > thresh)
print('%s:\t%i\t%i\n\t%i\t%i' % ('model', val[0, 0], val[0, 1],
val[1, 0], val[1, 1]))
print('-------------------')
def labeled_confusion_matrix(y_true, y_pred):
"""
Wrapper around the confusion matrix so it contains labels
for each of the cells
"""
cm = confusion_matrix(y_true, y_pred)
df = pd.DataFrame(cm,
columns=['neg pred', 'pos pred'],
index=['neg real', 'pos real'])
return df
# @profile
def generate_performance_table(test_df, neur, thresh, columns, metrics=None):
"""
Create the main results table for the paper
"""
fmt_str = '%.2f (%.2f)'
log_pred = test_df['logreg_prob'].values
y_true = test_df['vote'].values
if metrics is None:
metrics_names = ['AUC', 'AP', 'F1',
'Accuracy', 'Precision', 'Recall', 'Cohen']
metrics = [roc_auc_score, average_precision_score, f1_score,
accuracy_score, precision_score, recall_score, cohen_kappa_score]
binary = [False, False, True, True, True, True, True]
table_dict = []
# columns = ['model [5-vote] (std)',
# 'model [3-vote] (std)', 'neurologists [3-vote] (std)']
for met, is_bin in zip(metrics, binary):
results_dict_neur = leave_one_out_score(
test_df, neur, met) if is_bin else np.nan
results_dict_log = leave_one_out_score(
test_df, neur, met, y_pred_ext=log_pred > thresh if is_bin else log_pred)
average_score_neur = np.average(
list(results_dict_neur.values())) if is_bin else np.nan
std_score_neur = np.std(
list(results_dict_neur.values())) if is_bin else np.nan
average_score_log = np.average(list(results_dict_log.values()))
std_score_log = np.std(list(results_dict_log.values()))
score_5_vote = met(y_true, log_pred > thresh if is_bin else log_pred)
# table_dict.append({columns[2]: fmt_str % (average_score_neur, std_score_neur)
# if is_bin
# else 'N/A',
# columns[1]: fmt_str % (average_score_log, std_score_log),
# columns[0]: score_5_vote})
table_dict.append({columns[2]: average_score_neur
if is_bin
else np.nan,
columns[1]: average_score_log,
columns[0]: score_5_vote})
perf_df = pd.DataFrame(table_dict, index=metrics_names)
return perf_df
def get_help(key, config_file):
'''
Returns the comment associated with the key in the config file
'''
val_line = -1
found = False
lines = [l.strip() for l in open(config_file, 'r').readlines()]
for i, l in enumerate(lines):
if re.match('^\'%s\':.*' % key, l):
val_line = i
found = True
# Find description lines
descr_lines = []
for j in range(val_line - 1, 0, -1):
if re.match('^#.*', lines[j]):
descr_lines.insert(0, lines[j].strip('# '))
else:
break
description = ' '.join(descr_lines)
if found:
return description
else:
return ''
# @profile
def run_for_split(splt, gkf, df, X, y, neur):
try:
# for splt in tqdm.tqdm(range(1000)):
# Ensure the same patient does not occur in both train and test set
train_index, test_index = list(gkf.split(df.index, groups=df.clinic_id.values))[splt]
X_train = X[train_index, :]
y_train = y[train_index, :]
groups_train = df.clinic_id.values[train_index]
train_indices = df.index[train_index]
if not args['skip_first_phase']:
# Cross-validation
gkf_fold = flip_train_val(n_splits=args['n_crossval_splits'])
# Uncomment to use standard GroupKFold
# gkf_fold = GroupKFold(n_splits=args['n_crossval_splits'])
cross_results = {}
best_features = []
best_features_dict = {}
best_features_indiv = {}
for train_fold_index, test_fold_index in gkf_fold.split(X_train, y_train, groups_train):
X_fold_train = X_train[train_fold_index, :]
y_fold_train = y_train[train_fold_index, :]
X_fold_test = X_train[test_fold_index, :]
y_fold_test = y_train[test_fold_index, :]
for i, _ in enumerate(neur):
y_fold_train_neur = y_fold_train[:, i]
y_fold_test_neur = y_fold_test[:, i]
sets = ((X_fold_train[:, q].reshape((-1, 1)), y_fold_train[:, i], X_fold_test[:, q].reshape((-1, 1)), y_fold_test[:, i]) for q in range(X_fold_train.shape[-1]))
p = multiprocessing.Pool()
results = p.starmap(fit_and_score_fold, sets, chunksize=200)
p.close()
cross_results.setdefault(neur[i], []).append(results)
top_n_table = {}
# Extract the best features for each neurologist
neur_anom = {name: 'N%i' % (i + 1) for i, name in enumerate(neur)}
PEAKS_FEAT = -1
for name in neur:
local_best_features = np.argsort(np.average(
np.array(cross_results[name]), axis=0))[::-1][:TOP_N_FEAT]
ranks = np.argsort(np.average(
np.array(cross_results[name]), axis=0))[::-1].argsort()
best_features_scores = np.sort(np.average(
np.array(cross_results[name]), axis=0))[::-1][:TOP_N_FEAT]
unsorted_scores = np.average(np.array(cross_results[name]), axis=0)
for i in range(TOP_N_FEAT):
top_n_table.setdefault(i+1, {})['Feature %s' % neur_anom[name]] = descr[local_best_features[i]]
top_n_table.setdefault(i+1, {})['AUC %s' % neur_anom[name]] = '%.3f' % best_features_scores[i]
top_n_table.setdefault(i+1, {})['Rank %s' % neur_anom[name]] = i + 1
# Manually add the peaks feature
top_n_table.setdefault(TOP_N_FEAT + 1, {})['Feature %s' % neur_anom[name]] = descr[PEAKS_FEAT]
top_n_table.setdefault(TOP_N_FEAT + 1, {})['AUC %s' % neur_anom[name]] = '%.3f' % unsorted_scores[PEAKS_FEAT]
top_n_table.setdefault(TOP_N_FEAT + 1, {})['Rank %s' % neur_anom[name]] = ranks[PEAKS_FEAT]
best_features.append({'name': name, 'features': [descr[feat] for feat in local_best_features]})
best_features_indiv[name] = [descr[feat] for feat in local_best_features]
for feat in local_best_features:
best_features_dict.setdefault(feat, []).append(
np.array(cross_results[name])[:, feat])
# Print Table 4
# Split into 3 separate tables
top_ten_df = pd.DataFrame(top_n_table).T
column_order = sum([
[x, y, z] for x, y, z in zip(
sorted([key for key in top_ten_df.keys() if 'Rank' in key]),
sorted([key for key in top_ten_df.keys() if 'AUC' in key]),
sorted([key for key in top_ten_df.keys() if 'Feature' in key])
)
],
[])
for i in range(3):
with pd.option_context("max_colwidth", 1000):
s = top_ten_df[column_order].iloc[:, i * 6: (i*6 + 6)].to_latex(index=False)
# Bold the Approximate Entropy
s = re.sub(r'(ApEn[\w\\\_]+)', r'\\textbf{\1}', s)
s = re.sub(r'(.*%s.*)' % descr[-1], r'\\hline\n\1', s)
# if i == 0:
# print(s, file=open('table_4.txt', 'w'))
# else:
# print(s, file=open('table_4.txt', 'a'))
# Score the features across the neurologists
candidates = []
for feat, values in best_features_dict.items():
candidates.append({'name': descr[feat], # Descriptive name
'id': feat, # Index of the feature
'av_perf': np.average(values), # Average performance
'std_perf': np.std(values), # Standard deviation of the performance
'occurrence': len(values)}) # For how many neurologists does it occur in the top n?
# Print only features with high occurrence
max_occurrence = max([x['occurrence'] for x in candidates])
candidates = filter(lambda x: x['occurrence'] >= max_occurrence - 1,
candidates)
# Convert to pandas df for printing
print_df = pd.DataFrame(candidates)
# print(print_df)
'''
%%%%%%%%%%%%%%%%%%%%%%%%
From this we find that for the current split of train/test there are 2 features that occur in the
top 10 of 4 of the neurologists, namely CP_ML_StepDetect_l1pwc_10.rmsoff and ApEn2_02.
Judging from cross-validation alone, CP_ML_StepDetect_l1pwc_10.rmsoff seems to be the best feature.
But upon closer inspection we find that ApEn2_02 en ApEn2_01 together occur in the top ten of all
neurologists. So we opted for this feature instead. The performance difference between CP_ML_StepDetect_l1pwc_10.rmsoff
and ApEn2_02 is negligible anyway.
%%%%%%%%%%%%%%%%%%%%%%%%
'''
# Based on the analysis above, choose the ApEn2_02 feature.
FEAT = args['chosen_feature'] # For the final results, we used 847
# print('Chosen feature: %s' % descr[FEAT])
'''
%%%%%%%%%%%%%%%%%%%%%%%%
Now let's have a look at the performance on the held-out test set.
We'll train on the training set with labels based on the majority
vote.
%%%%%%%%%%%%%%%%%%%%%%%%
'''
df['apen'] = df['new_apen']
# df['apen'] = np.vstack(df.features)[:, FEAT]
y_train_vote = df.vote.values[train_index]
clf = classifier(class_weight='balanced', solver='liblinear')
clf.fit(X_train[:, FEAT].reshape((-1, 1)), y_train_vote)
y_train_pred = clf.predict_proba(X_train[:, FEAT].reshape((-1, 1)))[:, 1]
if args['prec_rec_workpoint']:
# Find precision-recall working point, i.e., the point where precision is approximately
# the same as the recall
prec, rec, thresholds = precision_recall_curve(y_train_vote, y_train_pred)
# plt.plot(prec, rec)
# plt.scatter(prec[np.argmin(np.abs(prec - rec))], rec[np.argmin(np.abs(prec - rec))])
# plt.show()
thresh = thresholds[np.argmin(np.abs(prec - rec))]
else:
# Find ROC working point, i.e., the point where tpr is approximately the same as the 1 - fpr
fpr, tpr, thresholds = roc_curve(y_train_vote, y_train_pred)
# plt.plot(fpr, tpr)
# plt.scatter(fpr[np.argmax(np.abs(tpr - fpr))], tpr[np.argmax(np.abs(tpr - fpr))])
# plt.show()
thresh = thresholds[np.argmax(tpr - fpr)]
# print('Chosen threshold: %.3f' % thresh)
# The FEAT value for which this occurs
w = clf.coef_[0][0]
c = clf.intercept_
# WARNING: This is specific for the logreg model!
morph_thresh = (np.log(- thresh / (thresh - 1.)) - c) / w
# print('morphology threshold: %.3f' % morph_thresh)
indiv_thresh = []
# Individual thresholds for each neurologist
for name in neur:
fpr, tpr, thresholds = roc_curve(df.loc[df.index[train_index]][name].values, X_train[:, FEAT].reshape((-1, 1)))
thresh_loc = thresholds[np.argmax(tpr - fpr)]
indiv_thresh.append(thresh_loc)
# print('Neurologist\'s thresholds: %s (%.3f)' % (str(indiv_thresh), np.average(indiv_thresh)))
# Table columns
columns = ['model [5-vote] (std)',
'model [3-vote] (std)', 'neurologists [3-vote] (std)']
label_5vote = [x for x in columns if '5-vote' in x][0]
if args['subsample']:
ss = ShuffleSplit(n_splits=args['n_subsample_splits'], test_size=0.8, random_state=321)
subset_generator = [test_subset
for _, test_subset in ss.split(test_index)]
else:
subset_generator = [np.arange(test_index.shape[0])]
votes_5_results = []
for test_subset_indices in subset_generator:
subset_indices = test_index[test_subset_indices]
test_df = df.loc[df.index[subset_indices]].copy()
X_test = X[subset_indices, :]
# y_test = y[test_index, :] -> individual labels not used in test set
y_pred = clf.predict_proba(X_test[:, FEAT].reshape((-1, 1)))[:, 1]
test_df['logreg_prob'] = y_pred
test_df['logreg'] = y_pred > thresh
# pt = generate_performance_table(test_df, neur, thresh, columns, metrics=None)
# votes_5_results.append(pt[label_5vote].values)
test_df = df.loc[df.index[test_index]].copy()
X_test = X[test_index, :]
y_pred = clf.predict_proba(X_test[:, FEAT].reshape((-1, 1)))[:, 1]
# Plot Figure 3
# For the samples shown in the paper, we'll consider these values for the apen and
# the corresponding classifications by the neurologists (5-vote)
feat_vals = [0.2, 0.5, 0.9]
classes = [0, 1, 1]
# plot_distribution_with_samples(test_df, feat_vals, classes, indiv_thresh, df, FEAT)
test_df['logreg_prob'] = y_pred
test_df['logreg'] = y_pred > thresh
### av_std = list(zip(np.average(votes_5_results, axis=0),
### np.std(votes_5_results, axis=0)))
# We will use the performance on the full test set for the final results, but one
# could also use the average across the subsampled test set. Uncomment to print
# these performances
# print('\n'.join(['%.2f (%.2f)' % (av, std) for av, std in av_std]))
# Generate Table 3
pt = generate_performance_table(test_df, neur, thresh, columns, metrics=None)
# pt[label_5vote] = ['%.2f (%.2f)' % (av, std) for av, std in zip(pt[label_5vote].values, np.array(av_std)[:, 1])]
return pt.iloc[:, [2, 1, 0]]
# print(pt.iloc[:, [2, 1, 0]].to_latex(float_format='%.2f'), file=open('%s_3_%i.txt' % (args['descriptor'], splt), 'w'))
# Print the confusion matrices
# print_metric_score(confusion_matrix, test_df,
# neur, test_df.vote.values, y_pred > thresh)
# Plot Figure 4
# plot_two_curves(test_df, neur, thresh)
except UndefinedMetricWarning:
return None
def run_for_args(args):
TOP_N_FEAT = args['top_n_feat']
if not os.path.isfile(args['annot_file']):
if args['annot_file'] == 'frontiers_dataset.p':
df_labels = create_dataframe()
# Cache for subsequent runs
df_labels.to_pickle('frontiers_dataset.p')
else:
raise Exception('Could not locate dataset file: %s' % args['annot_file'])
else:
df_labels = pd.read_pickle(args['annot_file'])
cache_archive_file = 'cache_archive.p'
cur_args_str = '_'.join(map(lambda k: '%s_%s' % (k[0], k[1]), args.items()))
if not os.path.isfile(cache_archive_file):
cache_archive = {}
else:
with open(cache_archive_file, 'rb') as f:
cache_archive = pickle.load(f)
if (not cur_args_str in cache_archive) or ('filter_apen' not in cache_archive[cur_args_str]):
p = multiprocessing.Pool()
f = functools.partial(calc_apen, filt=args['filter'], norm=True)
# apen_filtered_values = list(tqdm.tqdm(map(f, df_labels.groupby('timeseries_id').nth(0).iterrows()), total=df_labels.timeseries_id.nunique()))
apen_filtered_values = list(tqdm.tqdm(p.imap(f, df_labels.groupby('timeseries_id').nth(0).iterrows()), total=df_labels.timeseries_id.nunique()))
p.close()
for apen, (_, group) in zip(apen_filtered_values, df_labels.groupby('timeseries_id')):
df_labels.at[group.index, 'new_apen'] = apen
apen_filtered_values = np.vstack(df_labels.new_apen.values).ravel()
cache_archive.setdefault(cur_args_str, {})
cache_archive[cur_args_str].update({'filter_apen': apen_filtered_values})
with open(cache_archive_file, 'wb') as f:
pickle.dump(cache_archive, f)
else:
apen_filtered_values = cache_archive[cur_args_str]['filter_apen']
df_labels['new_apen'] = apen_filtered_values
# p = multiprocessing.Pool()
# f = functools.partial(calc_apen, filt=True, norm=True)
# apen_filtered_values = list(tqdm.tqdm(p.imap(f, df_labels.iterrows()), total=len(df_labels)))
# p.close()
# df_labels['new_apen'] = apen_filtered_values
# df_labels.to_pickle('real_apen_df_filtered.p')
# sys.exit()
if args['include_only'] != 'all':
if args['include_only'] not in df_labels.computer.unique():
raise Exception('Invalid machine type: %s. Should be one of {new, old}' %
args['include_only'])
df_labels = df_labels[df_labels.computer == args['include_only']]
# if args['remove_filtered']:
# df_labels = df_labels[df_labels.computer == 'new']
# # df_labels = df_labels[df_labels.computer == 'old']
neur = sorted(df_labels.name.unique().tolist())
# Determine the agreement between the neurologists
intra_dict_cohen = get_intrarater(df_labels, func=cohen_kappa_score)
intra_dict_agree = get_intrarater(df_labels, func=agreement_fraction)
# Remove doubles used for intra-rater
if args['discard_all_doubles']:
# Simply remove all visits that are double,
# a single visit has 4 measurements
df_labels = df_labels.groupby(
['visitid', 'name']).filter(lambda x: len(x) == 4)
else:
# Of the doubles used for the intrarater, use only those that have the same label
# If one of the neurologists was not consistent, we remove the TS from the dataset
df_labels['consistent_label'] = (df_labels
.groupby(['visitid', 'name', 'anatomy_side'])
.morph
.transform(lambda x: x.nunique() == 1))
df_labels = (df_labels
.groupby(['visitid', 'anatomy_side'])
.filter(lambda x: all(x.consistent_label.values)))
df_labels = (df_labels
.groupby(['visitid', 'name', 'anatomy_side'], as_index=False)
.nth(0))
print('# of TS remaining after removing doubles: %i' % (len(df_labels) / len(neur)))
# Remove TS with value 3 (bad data)
with_bad_data_count = len(df_labels)
df_labels = (df_labels
.groupby(['visitid', 'anatomy_side'])
.filter(lambda x: (x['morph'] != 3).all()))
print('# Removed due to bad data: %i / %i' %
(((with_bad_data_count - len(df_labels)) / len(neur)), with_bad_data_count / len(neur)))
# Generate agreement tables
df_agree = get_agreement(
df_labels, func=agreement_fraction, intra=intra_dict_agree)
df_cohen = get_agreement(
df_labels, func=cohen_kappa_score, intra=intra_dict_cohen)
df_summary = get_only_summaries(df_agree, df_cohen,
intra_agree=intra_dict_agree, intra_cohen=intra_dict_cohen)
# Write table 2
# print(df_summary.to_latex(float_format='%.2f'), file=open('table_2.txt', 'w'))
## Full agreement matrices
# print(df_agree.to_latex(float_format='%.2f'))
# print(df_cohen.to_latex(float_format='%.2f'))
# For convenience, create a column for each neurologist containing their label
df_tmp = (df_labels
.pivot_table(columns='name',
values='morph',
index=['visitid', 'anatomy_side'])
.reset_index()
)
df_ts_features = df_labels.groupby(['visitid', 'anatomy_side']).nth(0)
df_labels = pd.merge(df_tmp, df_ts_features, how='inner', on=['visitid', 'anatomy_side'])
df_labels.to_pickle('single_record_per_ts.p')
# Set labels values from 1 and 2 to 0 and 1
# Originally, 1 is normal, 2 is abnormal and 3 is bad data
# We'll use 0 and 1 for normal and abnormal for convenience
df_labels[neur] = df_labels[neur].apply(lambda x: x - 1)
# Vote - Create new column with the majority vote
df_labels['vote'] = (np.average(
df_labels[neur].values, axis=-1) > 0.5).astype(np.int8)
# Print the class imbalance
n_normal = len(df_labels.query('vote == 0'))
n_abnormal = len(df_labels.query('vote == 1'))
frac_normal = n_normal / (n_normal + n_abnormal)
frac_abnormal = n_abnormal / (n_normal + n_abnormal)
print('Class imbalance: %i / %i (%.2f / %.2f)' % (
n_normal,
n_abnormal,
frac_normal,
frac_abnormal
))
# print(df_labels.groupby(['vote', 'computer']).size())
df = df_labels
# Open the description file
with open('./feature_names.txt', 'r') as f:
descr = [x.strip() for x in f.readlines()]
assert len(descr) == df.iloc[0].features.shape[0]
df.reset_index(inplace=True, drop=True)
df.sort_values(by=['visitid', 'anatomy_side'], inplace=True)
'''
%%%%%%%%%%%%%%%%%%%%%%%%
In the first stage we will look for the best possible feature,
based on cross-validation on the training set. This is done
for each neurologist separately
%%%%%%%%%%%%%%%%%%%%%%%%
'''
# Create train and test set
# gkf = GroupKFold(n_splits=args['n_splits_train_test'])
gkf = GroupShuffleSplit(n_splits=args['n_splits'], random_state=1234)
# Adds a column with peak count (normalized)
df = find_peaks_ts(df)
X = np.repeat(np.vstack(df.new_apen.values).reshape((-1, 1)), df.iloc[0].features.shape[0], axis=1)
X = np.hstack([X, df['peaks'].values.reshape((-1, 1))])
# Add number of peaks to the description
descr.append('Number of peaks')
y = df[neur].values
if (not cur_args_str in cache_archive) or ('results' not in cache_archive[cur_args_str]):
p = multiprocessing.Pool()
f = functools.partial(run_for_split, gkf=gkf, df=df, X=X, y=y, neur=neur)
# res_dfs = list(tqdm.tqdm(map(run_for_split, range(args['n_splits'])), total=args['n_splits']))
res_dfs = list(tqdm.tqdm(p.imap(f, range(args['n_splits'])), total=args['n_splits']))
p.close()
cache_archive.setdefault(cur_args_str, {})
cache_archive[cur_args_str].update({'results': res_dfs})
with open(cache_archive_file, 'wb') as f:
pickle.dump(cache_archive, f)
# pickle.dump(res_dfs, open(results_cache, 'wb'))
else:
res_dfs = cache_archive[cur_args_str]['results']
print('Discarded %i splits due to no undefined metrics' % len([df for df in res_dfs if df is None]))
res_dfs = [df for df in res_dfs if df is not None]
full_results = pd.concat(res_dfs)
table = full_results.groupby(full_results.index).agg(['mean', 'std'])
# Force original order
return table.loc[res_dfs[0].index]
# for splt in [args['ind'] - 1]:
if __name__ == '__main__':
import warnings
# To catch MetricWarnings
warnings.filterwarnings('error')
# Load the configuration file
with open('config.yaml', 'r') as f:
config = yaml.load(f, Loader=yaml.FullLoader)
# Allow override with command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('-ind', type=int, default=-1)
parser.add_argument('-descriptor', type=str, default='table')
for key, val in config.items():
if isinstance(val, bool):
parser.add_argument('--%s' % key, action='store_%s' % str(not val).lower(),
help=get_help(key, config_file='config.yaml'))
else:
parser.add_argument('-%s' % key, type=type(val), default=val,
help=get_help(key, config_file='config.yaml'))
args = vars(parser.parse_args())
args.update({'skip_first_phase': True,
'prec_rec_workpoint': True,
'subsample': False})
# We'll consider 3 cases
# * Just new
# * Just old
# * Just old filtered
res_dfs = {}
tmp_args = args.copy()
tmp_args.update({'include_only': 'old',
'filter': False})
res_dfs['A [NF]'] = run_for_args(tmp_args)
tmp_args = args.copy()
tmp_args.update({'include_only': 'old',
'filter': True})
res_dfs['A [F]'] = run_for_args(tmp_args)
tmp_args = args.copy()
tmp_args.update({'include_only': 'new',
'filter': False})
res_dfs['B'] = run_for_args(tmp_args)
single_column = {}
# Make single column
for key, val in res_dfs.items():
new_df = {}
# The main votes
ul = np.unique([x[0] for x in val.keys()])
# Merge average and std into single string
sets = [sorted([k for k in val.keys() if k[0] in u], key=lambda k: k[1]) for u in ul]
for s in sets:
new_df[s[0][0] + '|' + key] = val[s].apply(lambda k: '%.2f (%.2f)' % (k[s[0]], k[s[1]]), axis=1).values
ndf = pd.DataFrame(data=new_df, index=val.index)
single_column[key] = ndf
tdf = functools.reduce(lambda left, right: left.join(right, how='inner'), single_column.values())
filt_inds = [k.split('|')[-1] for k in tdf.keys()]
new_columns = [(k.split('|')[0], f) for k, f in zip(tdf.keys(), filt_inds)]
tdf.columns = pd.MultiIndex.from_tuples(new_columns, names=['Rater', 'type'])
latex_table = tdf[sorted(tdf.keys())].to_latex(na_rep='N/A', bold_rows=True, multicolumn_format='c')
# Fix alignment
cur_al = re.findall('l{3,}', latex_table)[0]
new_al = 'l|' + '|'.join([''.join(['c'] * len(res_dfs)) for i in range(len(next(iter(single_column.values())).keys()))])
print(latex_table.replace(cur_al, new_al).replace('nan (nan)', 'N/A'))
<file_sep>import pandas as pd
import numpy as np
import tqdm
import yaml
import multiprocessing
import os
import frontiers_code as fc
class Data:
def __init__(self, v):
self.v = v
def approximate_entropy(y, mnom, rth):
"""Calculate the approximate entropy of a 1D timeseries
Code adapted from HCTSA package (https://github.com/benfulcher/hctsa)
"""
n = y.shape[-1] # Length of the TS
r = rth * np.std(y, axis=-1, ddof=1)
phi = np.zeros((2, 1))
ds = []
drs = []
for k in range(1, 3):
m = mnom + k - 1 # Pattern length
C = np.zeros((n - m + 1, 1))
x = np.zeros((n - m + 1, m))
# Form vector sequences x from the time series y
for i in range(n - m + 1):
x[i, :] = y[i:i + m]
ax = np.ones((n - m + 1, m));
for i in range(n - m + 1):
for j in range(m):
ax[:, j] = x[i,j];
d = abs(x - ax)
if m > 1:
d = np.max(d, axis=-1)
dr = d <= r
ds.append(d)
drs.append(dr)
C[i] = np.sum(dr) / (n - m + 1)
phi[k - 1] = np.mean(np.log(C))
return phi[0] - phi[1]
def normalize_apen(apen_val, nc):
'''Normalize the ApEn values by the values used in the paper
'''
apen_norm = - (apen_val - nc['median']) / (nc['iqr'] / 1.35)
apen_norm = 1. / (1 + np.exp(apen_norm))
apen_norm = (apen_norm - nc['min']) / (nc['max'] - nc['min'])
return apen_norm
def normalized_approximate_entropy(x, m=None, r=None):
nc = yaml.load(open('./normalization_constants.yaml', 'r'), Loader=yaml.FullLoader)
assert len(x) == 1920, 'Wrong number of samples for the timeseries, consider resampling'
# ts = scipy.stats.zscore(x[nc['cutoff']:])
ts = x[nc['cutoff']:]
if (m is None) and (r is None):
apen = approximate_entropy(ts, nc['m'], nc['r'])
else:
apen = approximate_entropy(ts, m, r)
norm_apen = normalize_apen(apen, nc)
return norm_apen
def main():
'''To illustrate the use of the normalized_approximate_entropy function we recalculate
the approximate entropy of the dataset and compare it to the original values.
'''
nc = yaml.load(open('./normalization_constants.yaml', 'r'), Loader=yaml.FullLoader)
AP_EN_ID=847
dataset_file = 'frontiers_dataset.p'
if not os.path.isfile(dataset_file):
df_labels = fc.create_dataframe()
# Cache for subsequent runs
df_labels.to_pickle(dataset_file)
df = pd.read_pickle(dataset_file)
# Calculate only for unique timeseries
df = df.groupby('timeseries_id').nth(0)
p = multiprocessing.Pool()
results = list(tqdm.tqdm(p.imap(normalized_approximate_entropy, df.timeseries.values, chunksize=1), total=len(df)))
p.close()
df['apen'] = results
# Check that they match the features in the dataset
results = np.hstack(df.apen.values)
apen_feat = df.features.apply(lambda k: k[AP_EN_ID])
max_difference = np.max(np.abs(results - apen_feat))
print('Maximum difference: %.2e' % max_difference)
if __name__ == "__main__":
main()
|
39a7bd9ef1e06959f26ac269aa7c7bf82f565c40
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
JanYperman/deciphering-morphology
|
fa638e81f9edadfdbed024cdab5fe4b1b854e26f
|
380ef73fb779307738f0761ca62fae014a0857e8
|
refs/heads/master
|
<repo_name>rajathvsm/Processing<file_sep>/AlphabetCounter/src/com/rvsm/alphabetcounter/AlphabetCounter.java
package com.rvsm.alphabetcounter;
/**@author <NAME>
* @brief Alphabet Counter accepts an input file
*/
import processing.core.PApplet;
import processing.core.PFont;
import processing.core.PGraphics;
public class AlphabetCounter extends PApplet {
/**
* A integer array of size 26 to hold the count of each alphabet
*/
private int[] character = new int[26];
/**
* The number of iterations
*/
private int count = 0;
/**
* A PFont object to use a particular font
*/
private PFont f;
/**
* A array of strings for storing the text from the file
*/
private String lines[];
/**
* String array to hold the command line arguments
*/
private static String args[];
/**
* A PGraphics object
*/
private PGraphics pg;
/**
* A unique ID to identify the version
*/
private static final long serialVersionUID = 2L;
/**
* The main function
*/
public static void main(String _args[]) {
args=_args;
PApplet.main(new String[] { AlphabetCounter.class.getName() });
}
/**
* The draw function. This gets called every time the screen is refreshed,
* till the program is exited.
*/
public void draw() {
noFill();
smooth();
stroke(200);
for (int i = 0; i < 26; i++) {
line(i * 30 + 50, 400, i * 30 + 50, 400 - character[i] / 300);
text((char) (i + 'a'), i * 30 + 50, 450);
if (count < lines.length) {
char[] subtext = lines[count++].toCharArray();
for (char character : subtext) {
this.character[character - 'a']++;
}
}
if (count % 100 == 0 || count == lines.length) {
pg.clear();
pg.beginDraw();
pg.background(30);
pg.stroke(255);
pg.textFont(f, 20);
pg.textAlign(CENTER);
pg.text(lines[count - 1], 200, 33);
pg.text("Completed " + count + " of " + lines.length
+ " lines.", 200, 66);
pg.endDraw();
image(pg, width / 2 - 200, 550);
}
}
/**
* Uncomment the following block to get connect the points and to get a shaded fill for the same.*/
/*for (int p = 0; p < character.length-1; p++) {
line(p * 30 + 50, 400 - character[p] / 300, (p + 1) * 30 + 50,
400 - character[p + 1] / 300);
}*/
}
/**
* This function reads the data from the file specified in the command line argument
*/
private void readData() {
try{
println(args[0]);
lines = loadStrings(args[0]);
}
catch(NullPointerException e ){
println("Invalid file. Exiting program\n");
exit();
}
catch(ArrayIndexOutOfBoundsException e ){
println("Invalid file. Exiting program\n");
exit();
}
}
/**
* This is the setup part, where we initialize the UI and load resources.
* This is just called once in every program. The draw method
* is called next.
*/
public void setup() {
size(900, 640);
frame.setTitle("Alphabet Counter");
background(0);
readData();
pg = createGraphics(400, 100);
frameRate(10000);
f = createFont("Monospace", 30, true);
}
}
|
e2462380da7079f0eee50eb9ad2273fd03cfccfe
|
[
"Java"
] | 1
|
Java
|
rajathvsm/Processing
|
9842e6f79845fb6ab4e856f9416b1c05c124d8ee
|
d80f85034d6b18282b030bf81210b3429a6f9007
|
refs/heads/master
|
<file_sep>var ball,img,paddle;
var edges;
function preload() {
ballimg = loadImage("ball.png");
paddleimg=loadImage("paddle.png")
}
function setup() {
createCanvas(400, 400);
ball = createSprite(40,200,20,20);
ball.addImage (ballimg);
ball.velocityX=9;
ball.velocityY=5;
paddle=createSprite(350,200,20,100);
paddle.addImage(paddleimg)
edges=createEdgeSprites();
}
function draw() {
background(255,223,0);
paddle.y=mouseY;
ball.bounceOff(edges[0]);
ball.bounceOff(edges[2]);
ball.bounceOff(edges[3]);
ball.bounceOff(paddle);
paddle.collide(edges);
drawSprites();
}
|
6f0fcb55263ee1d8ad296479818ee60d70cc3acb
|
[
"JavaScript"
] | 1
|
JavaScript
|
sharathu195/Squash-Game
|
28430542eb599269c7bc02071beb0f580fbf5439
|
72969474800602446585845df7ead15b3ea3b73f
|
refs/heads/master
|
<repo_name>engeld/autoblogger<file_sep>/src/html.c
#include <stdio.h>
#include "html.h"
void OutputHTMLHeader(void){
puts("<!DOCTYPE html>");
puts("<html>");
puts("<head>");
puts(" <title>Linkliste</title>");
puts("</head>");
puts("<body>");
}
void OutputHTMLFooter(void){
puts("</body>");
puts("</html>");
}
<file_sep>/src/html.h
#ifndef DE_HTMLH
#define DE_HTML_H
void OutputHTMLHeader(void);
void OutputHTMLFooter(void);
#endif
<file_sep>/README.md
autoblogger
===========
curates a link-blog using a link.txt file
### Required Input
a text file called `links.txt` using this syntax:
```
links
=====
yyyy-mm-dd
----------
#example-tag
http:/example.com
#another-example-tag
http://another-example.com
2014-11-24
----------
#programming
http://www.catb.org/esr/faqs/hacking-howto.html
http://www.hanselman.com/blog/HowDoYouOrganizeYourCode.aspx
```
### Expected Output
A simple, ready-to-be published html-page.
----
## FAQ
### Why did you use C as the programming language?
Because I can! Also, because my C is rusty and I wanted it to brush up using an interesting project I planned a long time ago. Maybe I'll change the programming language at some point, but for now it stays C.
### Why did you create this project?
I had this idea in my mind for a long time. When browsing on the net, I always keep a `link.txt` text file for dumping interesting links. I always wanted to create a browsable place for those interesting links!
<file_sep>/src/autoblogger.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "html.h"
int main( int argc, char *argv[] )
{
FILE *in;
int character;
int counter;
/* Handle arguments */
if( argc != 2 ){
fprintf( stderr, "Usage: %s <link.txt>\n", argv[0]);
exit( EXIT_FAILURE );
}
/* Handle file-opening */
in = fopen( argv[1], "r");
if( in == NULL ){
perror( "Unable to open the file" );
exit( EXIT_FAILURE );
}
OutputHTMLHeader();
/* loop through input file and process (depending on content) */
for(counter = 0; (character=getc(in)) != EOF; counter++){
/* printf( "%c", character); */
switch( character ){
case '=': /* all characters until the first equal sign belongs to the title */
printf( "<h1>" );
/* empty the char-bucket */
printf( "</h1>\n" );
break;
case '-':
printf( "<h2>" );
/* empty the char-bucket */
printf( "</h2>\n" );
break;
case '\n': /* 2 newlines => new section */
if( getc(in) == '\n'){
printf( "<p>" );
/* empty the bucket (loop through the links in it) */
printf( "</p>\n" );
}
break;
default:
/* printf( "%c", ch); */
/* add char to bucket */
break;
}
}
fclose( in );
OutputHTMLFooter();
return EXIT_SUCCESS;
}
<file_sep>/Makefile
CC=/usr/local/bin/gcc-4.9
CARGS=-O3 -g -c -ansi -Wall -pedantic
LARGS=
blog: autoblogger.o html.o
$(CC) -o blog autoblogger.o html.o $(LARGS)
autoblogger.o: src/autoblogger.c src src/html.h
$(CC) -o autoblogger.o src/autoblogger.c $(CARGS)
html.o: src/html.c src/html.h
$(CC) -o html.o src/html.c $(CARGS)
clean:
rm -f blog && rm -f *.o
|
6c3e918a6ee0eaa76ef92adf3d0a9dcb82417e06
|
[
"Markdown",
"C",
"Makefile"
] | 5
|
C
|
engeld/autoblogger
|
1a5b0e9d6798da09b644a1812a77348b076eff0b
|
a0769468b75624e988e0a2c28bc196d3020d4880
|
refs/heads/master
|
<repo_name>Skrubs/FlowerInvader<file_sep>/TheKidGame/src/thekidgame/angelo/entities/Player.java
package thekidgame.angelo.entities;
import javafx.geometry.Rectangle2D;
import javafx.scene.image.Image;
import thekidgame.angelo.Main;
import thekidgame.angelo.game.GameScene;
import thekidgame.angelo.game.GameTimer;
import thekidgame.angelo.util.Id;
import thekidgame.angelo.util.ImageLoader;
import thekidgame.angelo.util.Movement;
public class Player extends Sprite {
private Image[] downAnimation;
private Image[] leftAnimation;
private Image[] rightAnimation;
private Image[] upAnimation;
private int health = 40;
private final int MAXHEALTH = 100;
private double lastHealed = 0;
private boolean landed;
public Player(Image spriteImage, double posX, double posY, double velX, double velY, Enum<Id> id) {
super(spriteImage, posX, posY, velX, velY, id);
setSize(spriteImage);
landed = false;
}
@Override
public void setSize(Image spriteImage) {
if (spriteImage != null) {
this.setWidth(spriteImage.getWidth() + 30);
} else {
this.setWidth(20);
}
if (spriteImage != null) {
this.setHeight(spriteImage.getHeight() + 30);
} else {
this.setHeight(30);
}
}
@Override
public Rectangle2D getBounds() {
return new Rectangle2D(this.getPosX() + 5, this.getPosY() + 5, this.getWidth() - 10, this.getHeight() - 10);
}
public Rectangle2D pollinateBounds() {
double centerX = (this.getBounds().getMinX() + 18);
double centerY = (this.getBounds().getMinY() + 5);
return new Rectangle2D(centerX, centerY, 10, 20);
}
public void pollinate(Sprite s) {
if (this.pollinateBounds().intersects(s.getBounds())) {
if (this.health < this.MAXHEALTH && (GameTimer.getTimer() - lastHealed) > 1) {
health++;
lastHealed = GameTimer.getTimer();
}
}
}
public void playerImage() {
}
public void loadImageArray() {
downAnimation = new Image[2];
downAnimation[0] = ImageLoader.BEEs1;
downAnimation[1] = ImageLoader.BEEs2;
rightAnimation = new Image[2];
rightAnimation[0] = ImageLoader.BEEs3;
rightAnimation[1] = ImageLoader.BEEs4;
upAnimation = new Image[2];
upAnimation[0] = ImageLoader.BEEs5;
upAnimation[1] = ImageLoader.BEEs6;
leftAnimation = new Image[2];
leftAnimation[0] = ImageLoader.BEEs7;
leftAnimation[1] = ImageLoader.BEEs8;
}
public boolean getLanded() {
return landed;
}
public void setLanded(boolean landed) {
this.landed = landed;
}
public int getHealth() {
return health;
}
public Image[] getDownAnimation() {
return downAnimation;
}
public Image[] getLeftAnimation() {
return leftAnimation;
}
public Image[] getRightAnimation() {
return rightAnimation;
}
public Image[] getUpAnimation() {
return upAnimation;
}
public void movePlayer(Movement move) {
if (move.getInputList().contains("W")) {
this.setVelY(-3);
}
if (move.getInputList().contains("S")) {
this.setVelY(3);
}
if (move.getInputList().contains("D")) {
this.setVelX(3);
}
if (move.getInputList().contains("A")) {
this.setVelX(-3);
}
if (!move.getInputList().contains("W") && !move.getInputList().contains("S")) {
this.setVelY(0);
}
if (!move.getInputList().contains("D") && !move.getInputList().contains("A")) {
this.setVelX(0);
}
this.move();
}
}
<file_sep>/TheKidGame/src/thekidgame/angelo/entities/Sprite.java
package thekidgame.angelo.entities;
import javafx.geometry.Rectangle2D;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import thekidgame.angelo.util.Id;
public abstract class Sprite {
private double posX;
private double posY;
private double velX;
private double velY;
private double width;
private double height;
private Enum<Id> id;
private Image spriteImage;
private boolean isAlive;
public Sprite(Image spriteImage,double posX, double posY, double velX, double velY, Enum<Id> id) {
setSpriteImage(spriteImage);
this.posX = posX;
this.posY = posY;
this.velX = velX;
this.velY = velY;
setSize(spriteImage);
isAlive = true;
this.id = id;
}
/**
* Draw Debug mode traces bounding box for collision debug
* @param gc
*/
public void debugDraw(GraphicsContext gc) {
double x = this.getBounds().getMinX();
double y = this.getBounds().getMinY();
double w = this.getBounds().getMaxX() - x;
double h = this.getBounds().getMaxY() - y;
gc.strokeRect(x, y, w, h);
}
/**
* Set the width and height of the sprite based on the Image size
* @param spriteImage
*/
public void setSize(Image spriteImage) {
if(spriteImage != null) {
width = spriteImage.getWidth();
}else {
width = 20;
}
if(spriteImage != null) {
height = spriteImage.getHeight();
}else {
height = 10;
}
}
/**
* moves the sprite
*/
public void move() {
posX += velX;
posY += velY;
}
/**
* moves the sprite takes in a x and y
* @param velX
* @param velY
*/
public void move(double velX, double velY) {
posX += velX;
posY += velY;
}
/**
* move sprite on the x axis
* @param velX
*/
public void xMove(double velX) {
posX += velX;
}
/**
* move sprite on the y axis
* @param velY
*/
public void yMove(double velY) {
posY += velY;
}
/**
* gets the bounding box for the object
* @return
*/
public abstract Rectangle2D getBounds();
/**
* checks collision between two sprites
* @param s
* @return boolean
*/
public boolean collision(Sprite s) {
return this.getBounds().intersects(s.getBounds());
}
/**
* Checks collision between sprite and a rectangle
* @param r
* @return boolean
*/
public boolean objectCollision(Rectangle2D r) {
return this.getBounds().intersects(r);
}
//SETTERS AND GETTERS BEYOND THIS POINT
public double getPosX() {
return posX;
}
public void setPosX(double posX) {
this.posX = posX;
}
public double getPosY() {
return posY;
}
public void setPosY(double posY) {
this.posY = posY;
}
public double getVelX() {
return velX;
}
public void setVelX(double velX) {
this.velX = velX;
}
public double getVelY() {
return velY;
}
public void setVelY(double velY) {
this.velY = velY;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public Enum<Id> getId() {
return id;
}
public void setId(Enum<Id> id) {
this.id = id;
}
public Image getSpriteImage() {
return spriteImage;
}
public void setSpriteImage(Image spriteImage) {
if(spriteImage != null) {
this.spriteImage = spriteImage;
}else {
this.spriteImage = new Image(getClass().getResource("textures/missingimage.png").toExternalForm());
}
}
public boolean isAlive() {
return isAlive;
}
public void setAlive(boolean isAlive) {
this.isAlive = isAlive;
}
}
<file_sep>/TheKidGame/src/thekidgame/angelo/entities/Flower.java
package thekidgame.angelo.entities;
import java.util.ArrayList;
import javafx.geometry.Rectangle2D;
import javafx.scene.image.Image;
import thekidgame.angelo.game.GameTimer;
import thekidgame.angelo.util.Id;
import thekidgame.angelo.util.ImageLoader;
public class Flower extends Sprite {
private int health;
private static final int MAXHEALTH = 20;
private int growthStage;
private static final int MAX_GROWTH = 3;
private boolean isPollinated;
private double growthTimer;
public Flower(Image spriteImage, double posX, double posY, double velX, double velY, Enum<Id> id) {
super(spriteImage, posX, posY, velX, velY, id);
health = MAXHEALTH;
growthStage = 0;
isPollinated = false;
growthTimer = 0;
}
@Override
public Rectangle2D getBounds() {
return new Rectangle2D(this.getPosX()+5, this.getPosY()+5,this.getWidth()-5, this.getHeight()-5);
}
public void beingPollinated(Player player) {
if(this.getBounds().intersects(player.pollinateBounds())) {
isPollinated = true;
}else {
isPollinated = false;
growthTimer = GameTimer.getTimer();
}
if(isPollinated == true) {
if((GameTimer.getTimer() - growthTimer) > 5) {
growthTimer = GameTimer.getTimer();
if(growthStage + 1 <= 3) {
growthStage++;
System.out.println("My Growth Stage = " + growthStage);
}
}
}
this.setSpriteImage(flowerImage());
}
public Image flowerImage() {
if(growthStage == 0) {
return ImageLoader.FLOWER_BUD;
}else if(growthStage == 1) {
return ImageLoader.FLOWER_SPROUT;
}else if(growthStage == 2) {
return ImageLoader.FLOWER;
}else {
return ImageLoader.FLOWER;
}
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getGrowthStage() {
return growthStage;
}
public void setGrowthStage(int growthStage) {
this.growthStage = growthStage;
}
public boolean isPollinated() {
return isPollinated;
}
public void setPollinated(boolean isPollinated) {
this.isPollinated = isPollinated;
}
public static int getMaxhealth() {
return MAXHEALTH;
}
public static int getMaxGrowth() {
return MAX_GROWTH;
}
}
<file_sep>/TheKidGame/src/thekidgame/angelo/Main.java
package thekidgame.angelo;
import javafx.application.Application;
import javafx.stage.Screen;
import javafx.stage.Stage;
import thekidgame.angelo.menu.MainMenu;
import thekidgame.angelo.util.ImageLoader;
public class Main extends Application {
private static Stage window;
public static final double WINDOW_WIDTH = Screen.getPrimary().getBounds().getWidth();
public static final double WINDOW_HEIGHT = Screen.getPrimary().getBounds().getHeight();
private String title = "KidGame v0.1";
private String style = getClass().getResource("application.css").toExternalForm();
@Override
public void start(Stage primaryStage) {
window = primaryStage;
//LOAD IMAGELOADER
//ImageLoader loader = new ImageLoader();
window.setScene(MainMenu.getMainMenuScene(style));
window.sizeToScene();
window.setResizable(true);
window.setTitle(title);
window.show();
}
public String getStyle() {
return style;
}
public static Stage getWindow() {
return window;
}
public static void main(String[] args) {
launch(args);
}
}
<file_sep>/TheKidGame/src/thekidgame/angelo/game/Handler.java
package thekidgame.angelo.game;
public class Handler {
Game game;
public Handler(Game game) {
this.game = game;
}
}
<file_sep>/TheKidGame/src/thekidgame/angelo/game/GameScene.java
package thekidgame.angelo.game;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import thekidgame.angelo.Main;
public class GameScene {
private Group root;
private static Scene gameScene;
private Canvas canvas;
private GraphicsContext gc;
private GameTimer gameTimer;
public GameScene() {
initializeScene();
}
public void initializeScene() {
root = new Group();
gameScene = new Scene(root, Main.WINDOW_WIDTH, Main.WINDOW_HEIGHT);
canvas = new Canvas(gameScene.getWidth(), gameScene.getHeight());
gc = canvas.getGraphicsContext2D();
root.getChildren().add(canvas);
gameTimer = new GameTimer(this);
gameTimer.start();
}
public Group getRoot() {
return root;
}
public static Scene getGameScene() {
return gameScene;
}
public Canvas getCanvas() {
return canvas;
}
public GraphicsContext getGc() {
return gc;
}
}
|
b964386a535cb53a5e4e75af30a2a08f9d289b90
|
[
"Java"
] | 6
|
Java
|
Skrubs/FlowerInvader
|
7bb86e9e6ea096fdf9113610672f07f0c12de8bf
|
570582507f8e99be3d9c33c58de1eb9d006979f5
|
refs/heads/master
|
<file_sep># Project Title
This project is a part for my research project currently working on. We are using LifePo4wered(https://lifepo4wered.com/) a battery solution for raspberry pi,The LiFePO4wered/Pi3™ is a high performance battery power system for the Raspberry Pi. It can power a Raspberry Pi for 1 to 9 hours from the battery (depending on Raspberry Pi model, attached peripherals and system load) and can be left plugged in continuously. The objective was to run raspberry pi with a bunch of sensors take readings and then send data to the server and go off to sleep. Now the LiFePO4wered/Pi3™ helps to sleep put the raspberry and wake it up the highlight is that we sleep mode consumes 4 Mirco Ohms. For surveillance of the raspberry power consumption and live data feed using pubnub.
Currently in this version we can track the wakeup time average power consumption of raspberry pi during its working cycle and wake up time for its next cycle
## Getting Started
### Prerequisites
Required Software’s
```
Setting raspberry pi reference https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up/3
Setting the LifePo4wered on raspberry pi use reference https://lifepo4wered.com/files/LiFePO4wered-Pi3-Product-Brief.pdf
Use the following commands for installing Python
sudo apt-get install python3.6
sudo pip install 'pubnub>=4.1.2' or sudo pip3 install 'pubnub>=4.1.2'
(Depending on the version of pip you are using)
```
### Installing
Once all the Prerequisites are satisfied Follow this step to run on Raspberry Pi
```
Connect Raspberry pi to Network
Copy the startup.py to in raspberry pi and run the file
sudo python startup.py
run the Reader.html on pc.
```
Once the file starts running it will send out data to the webpage.
## Running the tests
If you want to run the file at startup of the raspberry pi follow the following steps
Sudo nano /etc/profile
Once file is opten go to the file end and paste the below command
Sudo python locationOf/startup.py
This will run the file each time you start the raspberry pi.
Uncommenting the last two line in the in the python code will shutdown the raspberry pi after the run is complete and then again wake up after 2 mins this process will be continuous and thus you won’t be able to interrupt it.
If you want to interrupt this then opent he SD card in the computer and edit the lines in the etc/profile file or comment the lines in from the startup.py file from your computer.
## Deployment
To make this a deployabble projet Kindly make autologin the Raspberry pi and put the program in the startup as mentioned int he Running the tests
## Demo


## Built With
* [LiFePO4wered/Pi3™]( https://lifepo4wered.com/) – API and Hardware
* [Python]( https://www.python.org/) - Python
* [Raspberry Pi]( https://www.raspberrypi.org/) – Raspberry Pi
* [PubNub]( https://www.pubnub.com/) - PubNub
* [Eon API]( https://www.pubnub.com/developers/eon/) – Eon API for graphs
## Authors
<NAME>
## Acknowledgments
* LiFePO4wered/Pi3™
* Pubnub
<file_sep>from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
import subprocess
import time
import datetime
import math
pnconfig = PNConfiguration()
pnconfig.publish_key ='pub-c-9c260cad-9e78-4bea-a3a9-f584ea818532'
pnconfig.subscribe_key = 'sub-c-2e6e94ce-305d-11e9-a223-2ae0221900a7'
pubnub = PubNub(pnconfig)
x=10
def callback(message, status):
print(message)
avg=0.0
count=0
while x>0:
x-=1
count+=1
time.sleep(1)
p = subprocess.check_output('lifepo4wered-cli get vbat',shell=True) ## Read BAttery Voltage
b1=round(float(p)/1000,5)
p = subprocess.check_output('lifepo4wered-cli get vout',shell=True) ## Read Raspberry Pi Voltage
r1=round(float(p)/1000,5)
data ={
"eon":{"Battery Voltage (Volts)":b1,"Raspberry Pi Voltage (Volts)":r1}
}
avg=avg+r1
data2={ "PL":20,"ON":round(avg/count,3),"W":"Working","S":x,"WT":"Not Set Yet"}
pubnub.publish().channel('test').message(data).pn_async(callback) ## Send Data to EON API for Graph
pubnub.publish().channel('test2').message(data2).pn_async(callback) ## Send Data
avg=round(avg/count,5)
now=str(datetime.datetime.now() + datetime.timedelta(minutes = 2))
data3={ "PL":0,"ON":avg,"W":"Sleeping Now","S":0,"WT":now}
pubnub.publish().channel('test2').message(data3).pn_async(callback)
### Uncomment only if you want this for Auto run the program on startup and then sleep and wake up after N Minutes
### You can change the wake time below from 2 to the number you want
### subprocess.call('lifepo4wered-cli set WAKE_TIME 2',shell=True)
### subprocess.call('sudo shutdown -h now',shell=True)
|
fa294d778eb7cb4fe52da56d247d113ee056d0e3
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
pinak93/RaspBerryPi_PowerUsage
|
6a13ceb4211492ddf1c11c31604a4340403c4492
|
7e1a19fd3207d6e71289c2b4dda48e337f0dd12f
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApi.Html5.Upload.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Test(string name, int product)
{
return View(product);
}
}
}
|
36c75bd0ced826fd3c8c0782098479fadd11fa01
|
[
"C#"
] | 1
|
C#
|
DeveloperHulk/WebApi.Html5.Upload
|
99d959e2a06ae021f1b2c8534dca466464075b31
|
340dda46e9d6e1a9f329f2439a154b6f2785001f
|
refs/heads/master
|
<repo_name>efkaldas/advertising_WebApp<file_sep>/src/Controller/ArticleController.php
<?php
namespace App\Controller;
use App\Entity\Advertisment;
use App\Entity\User;
use App\Controller\RegistrationController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
class ArticleController extends Controller
{
/**
* @Route("/", name="advertisment_list")
* @Method({"GET"})
*/
public function index()
{
$advertisments = $this->getDoctrine()->getRepository(Advertisment::class)->findAll();
return $this->render('advertisments/index.html.twig', array
('advertisments' => $advertisments));
}
/**
* @Route("/advertisment/new", name="new_advertisment")
* @Method({"GET", "POST"})
* @Security("has_role('ROLE_USER')")
*/
public function new(Request $request)
{
$advertisment = new Advertisment();
$advertisment->setDate(new \DateTime('now'));
$advertisment->setUser($this->getUser());
$form = $this->createFormBuilder($advertisment)
->add('title', TextType::class, array('attr' => array('class' => 'form-control')))
->add('body', TextareaType::class, array(
'required' => false,
'attr' => array('class' => 'form-control')
))
->add('save', SubmitType::class, array(
'label' => 'Create',
'attr' => array('class' => 'btn btn-primary mt-3')
))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$advertisment = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($advertisment);
$entityManager->flush();
return $this->redirectToRoute('advertisment_list');
}
return $this->render('advertisments/new.html.twig', array(
'form' => $form->createView()
));
}
/**
* @Route("/advertisment/{id}", name="advertisment_show")
*/
public function show($id) {
$advertisment = $this->getDoctrine()->getRepository(Advertisment::class)->find($id);
return $this->render('advertisments/show.html.twig', array
('advertisment' => $advertisment));
}
/**
* @Route("/advertisment/delete/{id}", name="advertisment_delete")
* @METHOD({"DELETE"})
*/
public function delete(Request $request, $id)
{
$advertisment = $this->getDoctrine()->getRepository(Advertisment::class)->find($id);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($advertisment);
$entityManager->flush();
$respones = new Response();
$response->send();
}
/**
* @Route("/own_list", name="own_list")
* @Method({"GET"})
*/
public function Own_adv(Request $request)
{
$advertisments = $this->getDoctrine()->getRepository(Advertisment::class)->findAll();
return $this->render('advertisments/own.html.twig', array
('advertisments' => $advertisments));
}
// /**
// * @Route("/advertisment/save")
// */
// public function save()
// {
// $entityManager = $this->getDoctrine()->getManager();
// $advertisment = new Advertisment();
// $advertisment->setTitle('Adv one');
// $advertisment->setBody('This is body');
// $entityManager->persist($advertisment);
// $entityManager->flush();
// return new Response('Saved adv
// '.$advertisment->getId());
// }
}<file_sep>/src/Entity/Advertisment.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use App\Entity\User;
/**
* @ORM\Entity(repositoryClass="App\Repository\AdvertismentRepository")
*/
class Advertisment
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="text", length=100)
*/
private $title;
/**
* @ORM\Column(type="text")
*/
private $body;
/**
* @var datetime $date
*
* @ORM\Column(type="datetime")
*/
private $date;
/**
* @var User
*
* @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
public function getId()
{
return $this->id;
}
public function getTitle()
{
return $this->title;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getBody()
{
return $this->body;
}
public function setBody($body)
{
$this->body = $body;
}
public function Getdate()
{
return $this->date;
}
public function setDate($date)
{
$this->date = $date;
return $this;
}
public function setUser(User $user)
{
$this->user = $user;
return $this;
}
public function getUser()
{
return $this->user;
}
/**
* @ORM\PrePersist
*/
public function prePersist()
{
if (!$this->getDate()) {
$this->setDate(new \DateTime());
}
}
}
<file_sep>/public/js/main.js
const advertsiments = document.getElementById('advertisments');
if(advertsiments)
{
advertsiments.addEventListener('click', e => {
if(e.target.className === 'btn btn-danger delete-advertisment')
{
if(confirm('Are you sure?'))
{
const id = e.target.getAttribute('data-id');
fetch(`/advertisment/delete/${id}`, {
method: 'DELETE'
}).then(res => window.location.reload());
}
}
})
}
|
90987fc8642e118e71d4f7541959f59d9202b988
|
[
"JavaScript",
"PHP"
] | 3
|
PHP
|
efkaldas/advertising_WebApp
|
eec828c61f11123dc3b5b41527b2a4dff8fc5762
|
65a2256a9ce066acc3a3c433dd343d4c1b587e13
|
refs/heads/master
|
<repo_name>hetoarte/proyecto-intro-a-la-ingenieria-<file_sep>/nomechocrud/mate 021/save_c.php
<?php
include("../db.php");
if (isset($_POST['save_task'])){
$title = $_POST['title'];
$link = $_POST['link'];
$query = "INSERT INTO certamenes(titulo, link) VALUES ('$title', '$link')";
$result = mysqli_query($conn, $query);
if (!$result) {
die("query failed");
}
$_SESSION['message'] = 'guardado satisfactoriamente';
header("location:mate 021.php");
}
if(isset($_GET['id'])){
$id = $_GET['id'] ;
$query = "DELETE FROM certamenes WHERE id = $id";
$result = mysqli_query($conn,$query);
if (!$result){
die("fail");
}
$_SESSION['message'] = 'eliminado satisfactoriamente';
header("location:mate 021.php");
}
?><file_sep>/nomechocrud/subir archivo.php
<?php include("db.php") ?>
<!DOCTYPE html>
<html lang="es">
<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>nomechomath</title>
<!--google fonts-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<!--bootstrap 4-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!--custom css-->
<link rel="stylesheet" href="css/main.css">
<!--font iconos-->
<script src="https://kit.fontawesome.com/0be153cc79.js" crossorigin="anonymous"></script>
</head>
<body>
<!--barra de navegacion-->
<nav class="navbar navbar-expand-lg navbar-light bg-info p-3">
<div class="container">
<a class="navbar-brand" href="index.php">nomechomath</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<?php
if (!empty($_SESSION['nombre'])){
echo '<p>Bienvenido, ' . $_SESSION["nombre"];
echo '<a href="cerrar.php"> Cerrar sesión';
}
?>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown p-1 px-3">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
cursos
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="mate 021/mate 021.php">mate 021</a>
<a class="dropdown-item" href="mate 022/mate 022.html">mate 022</a>
<a class="dropdown-item" href="mate 023/mate 023.html">mate 023</a>
<a class="dropdown-item" href="mate 024/mate 024.html">mate 024</a>
</div>
</li>
<li class="nav-item p-1 px-3">
<a class="nav-link" href="subir archivo.php">Subir material</a>
</li>
<li class="nav-item p-1 pl-3">
<a class="nav-link" href="nosotros.html">nosotros</a>
</li>
</ul>
</div>
</div>
</nav>
<!--subir archivos-->
<div class="container text-center">
<div>
<h2>Compartir material</h2>
</div>
<?php
if(isset($_SESSION['message'])) {?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<?= $_SESSION['message'] ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<?php unset($_SESSION['message']); } ?>
<hr>
<div>
<h2>Subir archivos</h2>
</div>
<form>
<div class="form-group">
<input type="file" class="form-control-file" id="exampleFormControlFile1">
<input type="submit" value="enviar">
</div>
</div>
</form>
</div>
<div class="container">
<h2 class="text-center">Compartir links</h2>
<form action="save_users.php" method="POST">
<div class="form-group">
<label for="exampleFormControlInput1">Link del video o archivo</label>
<p>puedes subir link de videos o compartir documentos de google drive entre otros, eso si asegurate de que el documento este publico...</P>
<input type="link" class="form-control" name="link"id="exampleFormControlInput1" placeholder="Link">
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Cursos</label>
<select class="form-control" name="mataria" id="exampleFormControlSelect1">
<option>MAT_021</option>
<option>MAT_022</option>
<option>MAT_023</option>
<option>MAT_024</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Descripcion</label>
<p>introduce a que contenido del ramo pertenece la materia..</p>
<textarea class="form-control" name="des" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<div class="text-center">
<input class="btn btn-primary" name="save_users" type="submit" value="enviar">
</div>
</form>
</div>
<!--tabla-->
<?php if((!empty($_SESSION['nombre']))){ ?>
<div class="container mt-4">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">eliminar</th>
<th scope="col">Cursos</th>
<th scope="col">Descricion</th>
<th scope="col">Documento</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM subidos_users";
$result_tasks = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result_tasks)){ ?>
<tr>
<td><a class="btn btn-danger" href="save_users.php?id=<?php echo $row['id']?>"><i class="far fa-trash-alt"></i></a></td>
<td><?php echo $row['mataria'] ?></td>
<td><?php echo $row['Descripcion'] ?></td>
<td><a href=<?php echo $row['link'] ?> class="list-group-item list-group-item-action">link</a></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
</div>
<!--integrantes del grupo -->
<div class="container ">
<h2 class="text-center">Contacto</h2>
<div>
<p class="text-center">Dudas o problemas con la plataforma comunicarse a la siguiente direccion de correo </p>
<p class="text-center"><EMAIL></p>
</div>
</div>
<!-- Footer -->
<footer class="page-footer font-small bg-info">
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2019 Copyright:
<a href="index.html"> nomechomath.com</a>
<a href="login.php">admin</a>
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
<!--bootstrap 4 script-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep>/js/fire.js
var db = firebase.firestore();
function guardar(){
var nombre = document.getElementById('nombre').value;
var link = document.getElementById('link').value;
var raiz = document.getElementById('raiz');
var ra = raiz.innerText
console.log(ra);
db.collection("mates").doc("mate1").collection("apuntes").add({
name: nombre,
link: link
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
var nombre = document.getElementById('nombre').value = '' ;
var link = document.getElementById('link').value = '' ;
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
}
// leer documentos
var tabla = document.getElementById("list-fire");
db.collection("mates").doc("mate1").collection("apuntes").get().then((querySnapshot) => {
tabla.innerHTML = '';
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${doc.data()}`);
tabla.innerHTML += `
<p> <a href= ${doc.data().link}> ${doc.data().name}</a> </p>
`
});
});
<file_sep>/nomechocrud/save_users.php
<?php
include("db.php");
if (isset($_POST['save_users'])){
$materia = $_POST['mataria'];
$link = $_POST['link'];
$descripcion = $_POST['des'];
$query = "INSERT INTO subidos_users(mataria, link, Descripcion) VALUES ('$materia', '$link', '$descripcion')";
$result = mysqli_query($conn, $query);
if (!$result) {
die("query failed");
}
$_SESSION['message'] = 'guardado satisfactoriamente';
header("location:subir archivo.php");
}
if(isset($_GET['id'])){
$id = $_GET['id'] ;
$query = "DELETE FROM subidos_users WHERE id = $id";
$result = mysqli_query($conn,$query);
if (!$result){
die("fail");
}
$_SESSION['message'] = 'eliminado satisfactoriamente';
header("location:subir archivo.php");
}
?><file_sep>/nomechocrud/save_task.php
<?php
include("db.php");
if (isset($_POST['save_task'])){
$title = $_POST['title'];
$link = $_POST['link'];
$query = "INSERT INTO test(titulo, link) VALUES ('$title', '$link')";
$result = mysqli_query($conn, $query);
if (!$result) {
die("query failed");
}
$_SESSION['message'] = 'guardado satisfactoriamente';
header("location:mate 021/mate 021.php");
}
?><file_sep>/nomechocrud/subir.php
<?php
require('db.php');
$temporal = $_FILES['archivo']['tmp_name'];
$archivo = $_FILES['archivo']['name'];
$tamano = $_FILES['archivo']['size'];
$tipo = $_FILES['archivo']['type'];
$fileNameCmps = explode(".", $archivo);
/*$extension = strtolower(end($fileNameCmps));*/
/*$newFileName = md5(time() . $archivo) . '.' . $extension;*/
$titulo = $_POST['titulo'];
/*$extensiones_posibles = array('jpg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc', 'pdf');
if (!in_array($extension, $extensiones_posibles)){
echo 'No se puede subir archivos con la extensión .'.$extension;
}
else{
if (move_uploaded_file($temporal, 'archivos_usuarios/'.$nombre)){
echo "El archivo ha sido cargado correctamente.";
}else{
echo "Ocurrió algún error al subir el fichero. No pudo guardarse.";
}
}
*/
if($archivo != "none"){
$fp = fopen($temporal, "rb");
$contenido = fread($fp, $tamano);
$contenido = addslashes($contenido);
fclose($fp);
$consulta = "INSERT INTO archivos VALUES (default, '$archivo', '$titulo', '$contenido', '$tipo')";
mysqli_query($con, $consulta);
if (mysqli_affected_rows($con) > 0){
echo "Operación exitosa";
}else{
echo "Error";
}
}
?><file_sep>/nomechocrud/mate 021/mate 021.php
<?php include("../db.php") ?>
<!DOCTYPE html>
<html lang="es">
<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>nomechomath</title>
<!--google fonts-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<!--bootstrap 4-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!--custom css-->
<link rel="stylesheet" href="../css/main.css">
<!--font iconos-->
<script src="https://kit.fontawesome.com/0be153cc79.js" crossorigin="anonymous"></script>
</head>
<body>
<!--barra de navegacion-->
<nav class="navbar navbar-expand-lg navbar-light bg-info p-3">
<div class="container">
<a class="navbar-brand" href="../index.html">nomechomath</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<?php
if (!empty($_SESSION['nombre'])){
echo '<p>Bienvenido, ' . $_SESSION["nombre"];
echo '<a href="../cerrar.php"> Cerrar sesión';
}
?>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown p-1 px-3">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
cursos
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="../mate 021/mate 021.php">mate 021</a>
<a class="dropdown-item" href="../mate 022/mate 022.html">mate 022</a>
<a class="dropdown-item" href="../mate 023/mate 023.html">mate 023</a>
<a class="dropdown-item" href="../mate 024/mate 024.html">mate 024</a>
</div>
</li>
<li class="nav-item p-1 px-3">
<a class="nav-link" href="../subir archivo.php">Subir material</a>
</li>
<li class="nav-item p-1 pl-3">
<a class="nav-link" href="../nosotros.html">nosotros</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div>
<h1 class="text-center">Matematicas 021</h1>
</div>
<?php
if(isset($_SESSION['message'])&&!empty($_SESSION['nombre'])) {?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<?= $_SESSION['message'] ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<?php unset($_SESSION['message']); } ?>
<hr>
<!--calculo y complemento -->
<div class=" d-flex justify-content-around">
<div class="list-group col-sm-3 col-md-3 col-5">
<span class="badge badge-info p-3 text-uppercase "><h5>Calculo</h5></span>
<a class="btn btn-light" href="Calculo/Limites.html" role="button">Limites</a>
<a class="btn btn-light" href="https://drive.google.com/file/d/1fCYBaurhJUV6vUs2E-yQh1x-IPZYHFQm/view?usp=sharing" role="button">Ejemplo</a>
<a class="btn btn-light" href="#" role="button">Funciones</a>
<a class="btn btn-light" href="Calculo/Limites.html" role="button">Limites</a>
<a class="btn btn-light" href="Calculo/Limites.html" role="button">Funciones</a>
<a class="btn btn-light" href="Calculo/Limites.html" role="button">Derivadas</a>
<a class="btn btn-light" href="Calculo/Limites.html" role="button">Inecuaciones</a>
<a class="btn btn-light" href="Calculo/Limites.html" role="button">Trigonometria</a>
</div>
<div class="list-group col-sm-3 col-md-3 co-5">
<span class="badge badge-info p-3 text-uppercase"><h5>Complemento</h5></span>
<a class="btn btn-light" href="Calculo/Limites.html" role="button">Trigonometria</a>
<a class="btn btn-light" href="#" role="button">Sumatorias</a>
<a class="btn btn-light" href="#" role="button">Geometria analitica</a>
<a class="btn btn-light" href="Calculo/Limites.html" role="button">Polinomios</a>
<a class="btn btn-light" href="Calculo/Limites.html" role="button">Fracciones parciales</a>
<a class="btn btn-light" href="Calculo/Limites.html" role="button">Formas polares</a>
<a class="btn btn-light" href="Calculo/Limites.html" role="button">Trigonometria</a>
<a class="btn btn-light" href="Calculo/Limites.html" role="button">Trigonometria</a>
</div>
</div>
</div>
<!--scroll resumenes y apuntes generales-->
<div class="container escrolear col-sm-7 col-md-7 col-11">
<div class="text-center">
<!-- apuntes y resumenes -->
<span class="badge badge-info p-3 text-uppercase .d-flex " style="width:100%; height:60px; border:0;"><h5>Apuntes y resumenes</h5></span>
<?php
if((!empty($_SESSION['nombre']))){ ?>
<form action = "../save_task.php" method="POST">
<input type="text" name="title" placeholder="nombre" class="form-control my-2">
<input type="url" name ="link" placeholder="link" class="form-control my-2">
<input class="btn btn-primary" name="save_task" type="submit" value="guardar">
</form>
<?php } ?>
</div>
<!--tabla con php-->
<div class="box">
<table class="table">
<thead >
<tr>
<th>documentos</th>
<?php if((!empty($_SESSION['nombre']))){ ?>
<th>acciones</th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM test";
$result_tasks = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result_tasks)){ ?>
<tr>
<td><a href=<?php echo $row['link'] ?> class="list-group-item list-group-item-action"><?php echo $row['titulo'] ?></a></td>
<?php if((!empty($_SESSION['nombre']))){ ?>
<td><a class="btn btn-danger" href="../delete.php?id=<?php echo $row['id']?>"><i class="far fa-trash-alt"></i></a></td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="list-group pt-5 pb-5">
<span class="badge badge-info p-3 text-uppercase .d-flex " style="width:100%; height:60px; border:0;"><h5 >Certamenes</h5></span>
<?php if((!empty($_SESSION['nombre']))){ ?>
<form action = "save_c.php" method="POST">
<input type="text" name="title" placeholder="nombre" class="form-control my-2">
<input type="url" name ="link" placeholder="link" class="form-control my-2">
<input class="btn btn-primary" name="save_task" type="submit" value="guardar">
</form>
<?php } ?>
<div class="box">
<table class="table">
<thead >
<tr>
<th>documentos</th>
<?php if((!empty($_SESSION['nombre']))){ ?>
<th>acciones</th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php
;
$query = "SELECT * FROM certamenes";
$result_tasks = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result_tasks)){ ?>
<tr>
<td><a href=<?php echo $row['link'] ?> class="list-group-item list-group-item-action"><?php echo $row['titulo'] ?></a></td>
<?php if((!empty($_SESSION['nombre']))){ ?>
<td><a class="btn btn-danger" href="save_c.php?id=<?php echo $row['id'];?> "><i class="far fa-trash-alt"></i></a></td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
<!-- Footer -->
<footer class="page-footer font-small bg-info">
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2019 Copyright:
<a href="../index.html"> nomechomath.com</a>
<a href="../login.php">admin</a>
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
<!--bootstrap 4 script-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep>/nomechocrud/validador.php
<?php
session_start();
if (!empty($_POST['submit'])){
if ((!empty($_POST['email'])) && (!empty($_POST['password']))){
$email = $_POST['email'];
$pass = $_POST['password'];
if ($email == '<EMAIL>' && $pass == '<PASSWORD>'){
$_SESSION['nombre'] = 'Héctor';
header("location: index.php");
}
else if ($email == '<EMAIL>' && $pass == '<PASSWORD>'){
$_SESSION['nombre'] = 'Francisco';
header("location: index.php");
}
else if ($email == '<EMAIL>' && $pass == '<PASSWORD>'){
$_SESSION['nombre'] = 'Mauricio';
header("location: index.php");
}
else{
$_SESSION['error'] = 1;
header("location: login.php");
}
}
}
else{
header("location: index.php");
}
?><file_sep>/nomechocrud/index.php
<?php include("db.php") ?>
<!DOCTYPE html>
<html lang="es">
<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>nomechomath</title>
<!--google fonts-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<!--bootstrap 4-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!--custom css-->
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<!--barra de navegacion-->
<nav class="navbar navbar-expand-lg navbar-light bg-info p-3">
<div class="container">
<a class="navbar-brand" href="index.php">nomechomath</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<?php
if (!empty($_SESSION['nombre'])){
echo '<p>Bienvenido, ' . $_SESSION["nombre"];
echo '<a href="cerrar.php"> Cerrar sesión';
}
?>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown p-1 px-3">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
cursos
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="mate 021/mate 021.php">mate 021</a>
<a class="dropdown-item" href="mate 022/mate 022.html">mate 022</a>
<a class="dropdown-item" href="mate 023/mate 023.html">mate 023</a>
<a class="dropdown-item" href="mate 024/mate 024.html">mate 024</a>
</div>
</li>
<li class="nav-item p-1 px-3">
<a class="nav-link" href="subir archivo.php">Subir material</a>
</li>
<li class="nav-item p-1 pl-3">
<a class="nav-link" href="nosotros.html">nosotros</a>
</li>
</ul>
</div>
</div>
</nav>
<!--imagenes -->
<div id="carouselExampleControls" class="carousel slide img-slide" data-ride="carousel">
<div class="carousel-inner ">
<div class="carousel-item active">
<img src="imagenes/prestigio.jpg" class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="imagenes/prestigio.jpg" class="d-block w-100" alt="not">
</div>
<div class="carousel-item">
<img src="imagenes/prestigio.jpg" class="d-block w-100" alt="not found">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<!--cursos-->
<!-- <div class="container botones">
<button type="button" class="btn btn-primary btn-lg bot">MAT 021</button>
<button type="button" class="btn btn-primary btn-lg bot">MAT 022</button>
<button type="button" class="btn btn-primary btn-lg bot">MAT 023</button>
<button type="button" class="btn btn-primary btn-lg bot">MAT 024</button>
</div> -->
<div class="container tex">
<h2 class="text-center">¿que es nomechomath?</h2>
<p> la pagina mas perrona para que nunca mas repruebas mate Lorem ipsum dolor sit, amet consectetur adipisicing elit. Animi aspernatur ea, commodi molestiae, veniam perspiciatis
consequatur dolorum doloremque cum eaque consequuntur eum adipisci at, fugit id inventore nemo perferendis! Ab.
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Est at, distinctio, labore nisi, voluptatem sapiente hic doloremque
porro cum rem debitis necessitatibus harum ducimus unde. Dignissimos quasi pariatur enim recusandae!</p>
<hr>
</div>
<!--integrantes del grupo -->
<div class="container ">
<h2 class="text-center">Contacto</h2>
<div>
<p class="text-center">Dudas o problemas con la plataforma comunicarse a la siguiente direccion de correo </p>
<p class="text-center"><EMAIL></p>
</div>
</div>
<!-- Footer -->
<footer class="page-footer font-small bg-info">
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2019 Copyright:
<a href="index.php"> nomechomath.com</a>
<a href="login.php">admin</a>
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
<!--bootstrap 4 script-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep>/nomechocrud/login.php
<!DOCTYPE html>
<?php session_start();?>
<html lang="es">
<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>nomechomath</title>
<!--google fonts-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<!--bootstrap 4-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!--custom css-->
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<!--barra de navegacion-->
<nav class="navbar navbar-expand-lg navbar-light bg-info p-3">
<div class="container">
<a class="navbar-brand" href="index.php">nomechomath</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<?php
if (!empty($_SESSION['nombre'])){
echo '<p>Bienvenido, ' . $_SESSION["nombre"];
echo '<a href="cerrar.php"> Cerrar sesión';
}
else{
echo '<a href="login.php">Iniciar sesión</a>';
}
?>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown p-1 px-3">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
cursos
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="mate 021/mate 021.php">MAT021</a>
<a class="dropdown-item" href="MAT022.php">MAT022</a>
<a class="dropdown-item" href="MAT023.php">MAT023</a>
<a class="dropdown-item" href="MAT024.php">MAT024</a>
</div>
</li>
<li class="nav-item p-1 px-3">
<a class="nav-link" href="subir archivo.php">Subir material</a>
</li>
<li class="nav-item p-1 pl-3">
<a class="nav-link" href="nosotros.html">nosotros</a>
</li>
</ul>
</div>
</div>
</nav>
<?php
if (!empty($_SESSION['error'])){
echo '<p>Datos incorrectos</p>';
}
?>
<!--login -->
<div class="container mt-4 text-center">
<form method="POST" action="validador.php">
<input type="email" name="email" placeholder='Email' required />
<input type='<PASSWORD>' name='password' placeholder='<PASSWORD>' required />
<input type='submit' name='submit' value='Acceder' />
</form>
</div>
<!--integrantes del grupo -->
<div class="container ">
<h2 class="text-center">Contacto</h2>
<div>
<p class="text-center">Dudas o problemas con la plataforma comunicarse a la siguiente direccion de correo </p>
<p class="text-center"><EMAIL></p>
</div>
</div>
<!-- Footer -->
<footer class="page-footer font-small bg-info">
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2019 Copyright:
<a> nomechomath.com</a>
<a href="login.php">admin</a>
<div id="contenido">
</div>
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
<script src="js/code.js"></script>
<script src="js/fire.js"></script>
<!--bootstrap 4 script-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
|
af1e61549343b3a5225232aeb899931a91de657b
|
[
"JavaScript",
"PHP"
] | 10
|
PHP
|
hetoarte/proyecto-intro-a-la-ingenieria-
|
691ed192a05bd28677427eaeb66554e8ac36b2d5
|
79bc374ee5370dfa307b6acbf9c9ba7ca70dd9f3
|
refs/heads/master
|
<file_sep>var responsiveNav = require('responsive-nav');
document.addEventListener('DOMContentLoaded', function (){
var nav = responsiveNav('.nav-collapse', {
transition:400,
insert:'after'
});
});<file_sep>var responsiveNav = require('responsive-nav')
var nav = responsiveNav('.nav-collapse', {
transition:400,
insert:'after'
})
<file_sep>var button, text, visible
button = document.querySelector('.show')
text = document.querySelector('.enquiries')
visible = false
text.classList.add('accessibly-hidden')
button.addEventListener('click', function() {
if (visible) {
text.classList.add('accessibly-hidden')
} else {
text.classList.remove('accessibly-hidden')
}
visible = !visible
})
<file_sep># SVG Sprite
Install dependencies `npm install`
Run `npm run sprite`<file_sep># Compiling Tools
Simple examples of compile tools using NPM scripts.
## Requirements
Nodejs
## ESLint
Helps to detect errors and potential problems in your JavaScript. Watches all JavaScript files for changes.
### Instructions
1. Install Node modules `npm install`
2. Lint JavaScript `npm run compile:js`
## Sass
Basic Sass configuration and setup, uses node-sass to compile Sass to CSS. Watches all Sass files for changes.
### Instructions
1. Install Node modules `npm install`
2. Watch for changes and compile SCSS to CSS `npm run compile:sass`
## SVG Sprite / Sass SVG Sprite
Automated SVG spriting.
### Instructions
1. Install Node modules `npm install`
2. compile Sprite `npm run sprite`
## Browserify / ESLint Browserify / ESLint Browserify Minifyify
Browserify lets you require modules in the browser and bundles all your dependencies. Example with ESLint lints JavaScript before bundling and the example with Minifyify compresses JavaScript after bundling and maintains a sourcemap for easier debugging in the browser. Watches all JavaScript files for changes.
### Instructions
1. Install Node modules `npm install`
2. compile JavaScript `npm run compile:js`
## Critical
Critical extracts & inlines critical-path (above-the-fold) CSS from HTML.
### Instructions
1. Install Node modules `npm install`
2. compile JavaScript `npm run critical`
## Browser-sync
Browser-sync updates the browser automatically every time you save a change to your project files.
### Instructions
1. Install Node modules `npm install`
2. Sync browser `npm run browser-sync`
## Licence
Licensed under MIT Licence
|
5aee538cf382f93870eb4ac3ede711e539ea3a2f
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
mauricevancooten/build-tools
|
304b542b0d7d242b0d3ccc8b4c9b635571d65af9
|
d97273d5eceefb4552811b536834947d285b029f
|
refs/heads/master
|
<repo_name>dungbk34/twitter-api-get-data<file_sep>/app.py
# -*- coding: utf-8 -*-
import os
import tweepy as tw
import pandas as pd
from datetime import datetime, timedelta
import json
consumer_key = 'Nfl9DbPnaWOyf3nsXFie2M9FL'
consumer_secret = '<KEY>'
access_token = '<KEY>'
access_token_secret = '<KEY>'
auth = tw.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tw.API(auth, wait_on_rate_limit=True)
##############################################################
# Tweets
# Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user’s friends. This is the equivalent of /timeline/home on the Web.
# Parameters:
# since_id – Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
# max_id – Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
# count – The number of results to try and retrieve per page.
# page – Specifies the page of results to retrieve. Note: there are pagination limits.
# Return type:
# list of Status objects
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# f = open('home_timeline.txt', 'w+')
# for status in tw.Cursor(api.home_timeline).items(1):
# f.write(str(status))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
##############################################################
# API.user_timeline([id/user_id/screen_name][, since_id][, max_id][, count][, page])
# Returns the 20 most recent statuses posted from the authenticating user or the user specified. It’s also possible to request another user’s timeline via the id parameter.
# Parameters:
# id – Specifies the ID or screen name of the user.
# user_id – Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
# screen_name – Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
# since_id – Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
# max_id – Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
# count – The number of results to try and retrieve per page.
# page – Specifies the page of results to retrieve. Note: there are pagination limits.
# Return type:
# list of Status object
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# f = open('user_timeline.txt', 'w+')
# for status in api.user_timeline('@Cristiano', count = 1):
# f.write(str(status))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
##############################################################
# API.statuses_lookup(id_[, include_entities][, trim_user][, map_][, include_ext_alt_text][, include_card_uri])
# Returns full Tweet objects for up to 100 tweets per request, specified by the id_ parameter.
# Parameters:
# id_ – A list of Tweet IDs to lookup, up to 100
# include_entities – The entities node will not be included when set to false. Defaults to true.
# trim_user – A boolean indicating if user IDs should be provided, instead of complete user objects. Defaults to False.
# map_ – A boolean indicating whether or not to include tweets that cannot be shown. Defaults to False.
# include_ext_alt_text – If alt text has been added to any attached media entities, this parameter will return an ext_alt_text value in the top-level key for the media entity.
# include_card_uri – A boolean indicating if the retrieved Tweet should include a card_uri attribute when there is an ads card attached to the Tweet and when that card was attached using the card_uri value.
# Return type:
# list of Status objects
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# tweet id = 1179142471542067201
# f = open('statuses_lookup.txt', 'w+')
# for status in api.statuses_lookup(id_ = [1179142471542067201]):
# # Process a single status
# f.write(str(status))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
##############################################################
# API.retweets_of_me([since_id][, max_id][, count][, page])
# Returns the 20 most recent tweets of the authenticated user that have been retweeted by others.
# Parameters:
# since_id – Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
# max_id – Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
# count – The number of results to try and retrieve per page.
# page – Specifies the page of results to retrieve. Note: there are pagination limits.
# Return type:
# list of Status objects
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# f = open('retweets_of_me.txt', 'w+')
# for status in api.retweets_of_me(count = 1):
# f.write(str(status))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
##############################################################
# API.mentions_timeline([since_id][, max_id][, count])
# Returns the 20 most recent mentions, including retweets.
# Parameters:
# since_id – Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
# max_id – Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
# count – The number of results to try and retrieve per page.
# Return type:
# list of Status objects
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# f = open('mentions_timeline.txt', 'w+')
# for status in api.mentions_timeline(count = 1):
# f.write(str(status))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
### Tweets method
##############################################################
# Status methods
# API.get_status(id[, trim_user][, include_my_retweet][, include_entities][, include_ext_alt_text][, include_card_uri])
# Returns a single status specified by the ID parameter.
# Parameters:
# id – The numerical ID of the status.
# trim_user – A boolean indicating if user IDs should be provided, instead of complete user objects. Defaults to False.
# include_my_retweet – A boolean indicating if any Tweets returned that have been retweeted by the authenticating user should include an additional current_user_retweet node, containing the ID of the source status for the retweet.
# include_entities – The entities node will not be included when set to false. Defaults to true.
# include_ext_alt_text – If alt text has been added to any attached media entities, this parameter will return an ext_alt_text value in the top-level key for the media entity.
# include_card_uri – A boolean indicating if the retrieved Tweet should include a card_uri attribute when there is an ads card attached to the Tweet and when that card was attached using the card_uri value.
# Return type:
# Status object
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# # tweet id = 1179332900715667457
# f = open('get_status.txt', 'w+')
# status = api.get_status(id = 1179332900715667457)
# # Process a single status
# f.write(str(status))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
##############################################################
# API.retweeters(id[, cursor][, stringify_ids])
# Returns up to 100 user IDs belonging to users who have retweeted the Tweet specified by the id parameter.
# Parameters:
# id – The numerical ID of the status.
# cursor – Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned to in the response body’s next_cursor and previous_cursor attributes to page back and forth in the list.
# stringify_ids – Have ids returned as strings instead.
# Return type:
# list of Integers
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# # tweet id = 1179332900715667457
# f = open('retweeters.txt', 'w+')
# retweeters = api.retweeters(id = 1179332900715667457)
# # Process a single status
# f.write(str(retweeters))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
##############################################################
# API.retweets(id[, count])
# Returns up to 100 of the first retweets of the given tweet.
# Parameters:
# id – The numerical ID of the status.
# count – Specifies the number of retweets to retrieve.
# Return type:
# list of Status objects
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# # tweet id = 1179332900715667457
# f = open('retweets.txt', 'w+')
# for status in api.retweets(id = 1179332900715667457, count = 1):
# f.write(str(status))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
### User method
##############################################################
# API.get_user(id/user_id/screen_name)
# Returns information about the specified user.
# Parameters:
# id – Specifies the ID or screen name of the user.
# user_id – Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
# screen_name – Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
# Return type:
# User object
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
## user screen name = '@Cristiano'
# f = open('get_user.txt', 'w+')
# user = api.get_user('@Cristiano')
# f.write(str(user))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
##############################################################
# API.friends(id/user_id/screen_name)
# Returns information about the specified user.
# Parameters:
# id – Specifies the ID or screen name of the user.
# user_id – Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
# screen_name – Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
# Return type:
# User object
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
## user screen name = '@Cristiano'
# f = open('friends.txt', 'w+')
# for user in api.friends('@Cristiano', count = 5):
# f.write(str(user))
# f.close()
#
# # >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
##############################################################
# API.followers(id/user_id/screen_name)
# Returns information about the specified user.
# Parameters:
# id – Specifies the ID or screen name of the user.
# user_id – Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
# screen_name – Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
# Return type:
# User object
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
## user screen name = '@Cristiano'
# f = open('followers.txt', 'w+')
# for user in api.followers('@Cristiano', count = 5):
# f.write(str(user))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
##############################################################
# API.lookup_users([user_ids][, screen_names][, include_entities][, tweet_mode])
# Returns fully-hydrated user objects for up to 100 users per request.
# There are a few things to note when using this method.
# You must be following a protected user to be able to see their most recent status update. If you don’t follow a protected user their status will be removed.
# The order of user IDs or screen names may not match the order of users in the returned array.
# If a requested user is unknown, suspended, or deleted, then that user will not be returned in the results list.
# If none of your lookup criteria can be satisfied by returning a user object, a HTTP 404 will be thrown.
# Parameters:
# user_ids – A list of user IDs, up to 100 are allowed in a single request.
# screen_names – A list of screen names, up to 100 are allowed in a single request.
# include_entities – The entities node will not be included when set to false. Defaults to true.
# tweet_mode – Valid request values are compat and extended, which give compatibility mode and extended mode, respectively for Tweets that contain over 140 characters.
# Return type:
# list of User object
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
## user screen name = '@Cristiano'
# f = open('lookup_users.txt', 'w+')
# for user in api.lookup_users(['@BarackObama', '@realDonaldTrump']):
# f.write(str(user))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
##############################################################
# API.search_users(q[, count][, page])
# Run a search for users similar to Find People button on Twitter.com; the same results returned by people search on Twitter.com will be returned by using this API (about being listed in the People Search). It is only possible to retrieve the first 1000 matches from this API.
# Parameters:
# q – The query to run against people search.
# count – Specifies the number of statuses to retrieve. May not be greater than 20.
# page – Specifies the page of results to retrieve. Note: there are pagination limits.
# Return type:
# list of User objects
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
## search name = 'cristiano'
# f = open('search_users.txt', 'w+')
# for user in api.search_users(q = 'cristiano', count = 1):
# f.write(str(user))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# #Friendship Methods
### skip this method
#############################################################
# API.show_friendship(source_id/source_screen_name, target_id/target_screen_name)
# Returns detailed information about the relationship between two users.
# Parameters:
# source_id – The user_id of the subject user.
# source_screen_name – The screen_name of the subject user.
# target_id – The user_id of the target user.
# target_screen_name – The screen_name of the target user.
# Return type:
# Friendship object
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
## friend name = '@Snon28281023'
# f = open('show_friendship.txt', 'w+')
# friendship = api.show_friendship(source_screen_name = '@dungbk6', target_screen_name = '@Snon28281023')
# f.write(str(friendship))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#############################################################
# API.friends_ids(id/screen_name/user_id[, cursor])
# Returns an array containing the IDs of users being followed by the specified user.
# Parameters:
# id – Specifies the ID or screen name of the user.
# screen_name – Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
# user_id – Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
# cursor – Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned to in the response body’s next_cursor and previous_cursor attributes to page back and forth in the list.
# Return type:
# list of Integers
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
## friend name = '@Cristiano'
# f = open('friends_ids.txt', 'w+')
# friends_ids = api.friends_ids(screen_name = '@Cristiano')
# f.write(str(friends_ids))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#############################################################
# API.followers_ids(id/screen_name/user_id)
# Returns an array containing the IDs of users following the specified user.
# Parameters:
# id – Specifies the ID or screen name of the user.
# screen_name – Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
# user_id – Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
# cursor – Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned to in the response body’s next_cursor and previous_cursor attributes to page back and forth in the list.
# Return type:
# list of Integers
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
## friend name = '@Cristiano'
# f = open('followers_ids.txt', 'w+')
# followers_ids = api.followers_ids(screen_name = '@Cristiano')
# f.write(str(followers_ids))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#############################################################
# API.lists_all([screen_name][, user_id][, reverse])
# Returns all lists the authenticating or specified user subscribes to, including their own. The user is specified using the user_id or screen_name parameters. If no user is given, the authenticating user is used.
# A maximum of 100 results will be returned by this call. Subscribed lists are returned first, followed by owned lists. This means that if a user subscribes to 90 lists and owns 20 lists, this method returns 90 subscriptions and 10 owned lists. The reverse method returns owned lists first, so with reverse=true, 20 owned lists and 80 subscriptions would be returned.
# Parameters:
# screen_name – Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
# user_id – Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
# reverse – A boolean indicating if you would like owned lists to be returned first. See description above for information on how this parameter works.
# Return type:
# list of List objects
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
## screen_name = '@Cristiano'
# f = open('lists_all.txt', 'w+')
# lists_all = api.lists_all()
# f.write(str(lists_all))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#############################################################
# API.lists_memberships([screen_name][, user_id][, filter_to_owned_lists][, cursor][, count])
# Returns the lists the specified user has been added to. If user_id or screen_name are not provided, the memberships for the authenticating user are returned.
# Parameters:
# screen_name – Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
# user_id – Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
# filter_to_owned_lists – A boolean indicating whether to return just lists the authenticating user owns, and the user represented by user_id or screen_name is a member of.
# cursor – Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned to in the response body’s next_cursor and previous_cursor attributes to page back and forth in the list.
# count – The number of results to try and retrieve per page.
# Return type:
# list of List objects
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# f = open('lists_memberships.txt', 'w+')
# lists_memberships = api.lists_memberships()
# f.write(str(lists_memberships))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#############################################################
# API.lists_subscriptions([screen_name][, user_id][, cursor][, count])
# Obtain a collection of the lists the specified user is subscribed to, 20 lists per page by default. Does not include the user’s own lists.
# Parameters:
# screen_name – Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
# user_id – Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
# cursor – Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned to in the response body’s next_cursor and previous_cursor attributes to page back and forth in the list.
# count – The number of results to try and retrieve per page.
# Return type:
# list of List objects
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# f = open('lists_subscriptions.txt', 'w+')
# lists_subscriptions = api.lists_subscriptions()
# f.write(str(lists_subscriptions))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#############################################################
# API.list_timeline(list_id/slug[, owner_id/owner_screen_name][, since_id][, max_id][, count][, include_entities][, include_rts])
# Returns a timeline of tweets authored by members of the specified list. Retweets are included by default. Use the include_rts=false parameter to omit retweets.
# Parameters:
# list_id – The numerical id of the list.
# slug – You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you’ll also have to specify the list owner using the owner_id or owner_screen_name parameters.
# owner_id – The user ID of the user who owns the list being requested by a slug.
# owner_screen_name – The screen name of the user who owns the list being requested by a slug.
# since_id – Returns only statuses with an ID greater than (that is, more recent than) the specified ID.
# max_id – Returns only statuses with an ID less than (that is, older than) or equal to the specified ID.
# count – The number of results to try and retrieve per page.
# include_entities – The entities node will not be included when set to false. Defaults to true.
# include_rts – A boolean indicating whether the list timeline will contain native retweets (if they exist) in addition to the standard stream of tweets. The output format of retweeted tweets is identical to the representation you see in home_timeline.
# Return type:
# list of Status objects
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# # list_id = 1179806423384870912
# f = open('list_timeline.txt', 'w+')
# status = api.list_timeline(list_id = 1179806423384870912)
# f.write(str(status))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#############################################################
# API.get_list(list_id/slug[, owner_id/owner_screen_name])
# Returns the specified list. Private lists will only be shown if the authenticated user owns the specified list.
# Parameters:
# list_id – The numerical id of the list.
# slug – You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you’ll also have to specify the list owner using the owner_id or owner_screen_name parameters.
# owner_id – The user ID of the user who owns the list being requested by a slug.
# owner_screen_name – The screen name of the user who owns the list being requested by a slug.
# Return type:
# List object
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# # list_id = 1179806423384870912
# f = open('get_list.txt', 'w+')
# get_list = api.get_list(list_id = 1179806423384870912)
# f.write(str(get_list))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#############################################################
# API.list_members(list_id/slug[, owner_id/owner_screen_name][, cursor])
# Returns the members of the specified list.
# Parameters:
# list_id – The numerical id of the list.
# slug – You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you’ll also have to specify the list owner using the owner_id or owner_screen_name parameters.
# owner_id – The user ID of the user who owns the list being requested by a slug.
# owner_screen_name – The screen name of the user who owns the list being requested by a slug.
# cursor – Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned to in the response body’s next_cursor and previous_cursor attributes to page back and forth in the list.
# Return type:
# list of User objects
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# # list_id = 1179806423384870912
# f = open('list_members.txt', 'w+')
# list_members = api.list_members(list_id = 1179806423384870912)
# f.write(str(list_members))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#############################################################
# API.show_list_member(list_id/slug, screen_name/user_id[, owner_id/owner_screen_name])
# Check if the specified user is a member of the specified list.
# Parameters:
# list_id – The numerical id of the list.
# slug – You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you’ll also have to specify the list owner using the owner_id or owner_screen_name parameters.
# screen_name – Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
# user_id – Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
# owner_id – The user ID of the user who owns the list being requested by a slug.
# owner_screen_name – The screen name of the user who owns the list being requested by a slug.
# Return type:
# User object if user is a member of list
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# # list_id = 1179806423384870912
## friend name = '@Snon28281023'
# f = open('show_list_member.txt', 'w+')
# show_list_member = api.show_list_member(list_id = 1179806423384870912, screen_name = '@Snon28281023')
# f.write(str(show_list_member))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#############################################################
# API.list_subscribers(list_id/slug[, owner_id/owner_screen_name][, cursor][, count][, include_entities][, skip_status])
# Returns the subscribers of the specified list. Private list subscribers will only be shown if the authenticated user owns the specified list.
# Parameters:
# list_id – The numerical id of the list.
# slug – You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you’ll also have to specify the list owner using the owner_id or owner_screen_name parameters.
# owner_id – The user ID of the user who owns the list being requested by a slug.
# owner_screen_name – The screen name of the user who owns the list being requested by a slug.
# cursor – Breaks the results into pages. Provide a value of -1 to begin paging. Provide values as returned to in the response body’s next_cursor and previous_cursor attributes to page back and forth in the list.
# count – The number of results to try and retrieve per page.
# include_entities – The entities node will not be included when set to false. Defaults to true.
# skip_status – A boolean indicating whether statuses will not be included in the returned user objects. Defaults to false.
# Return type:
# list of User objects
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# # list_id = 1179806423384870912
# f = open('list_subscribers.txt', 'w+')
# list_subscribers = api.list_subscribers(list_id = 1179806423384870912)
# f.write(str(list_subscribers))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#############################################################
# API.show_list_subscriber(list_id/slug, screen_name/user_id[, owner_id/owner_screen_name])
# Check if the specified user is a subscriber of the specified list.
# Parameters:
# list_id – The numerical id of the list.
# slug – You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you’ll also have to specify the list owner using the owner_id or owner_screen_name parameters.
# screen_name – Specifies the screen name of the user. Helpful for disambiguating when a valid screen name is also a user ID.
# user_id – Specifies the ID of the user. Helpful for disambiguating when a valid user ID is also a valid screen name.
# owner_id – The user ID of the user who owns the list being requested by a slug.
# owner_screen_name – The screen name of the user who owns the list being requested by a slug.
# Return type:
# User object if user is subscribed to list
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# # list_id = 1179806423384870912
# f = open('show_list_subscriber.txt', 'w+')
# try:
# show_list_subscriber = api.show_list_subscriber(list_id = 1179806423384870912, screen_name = '@Snon28281023')
# f.write(str(show_list_subscriber))
# except(NameError, tw.error.TweepError):
# f.write("User doesn't subcribe list")
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# $$$$$$$$$$$$$$$$$$$$$$$$$ Trends Methods $$$$$$$$$$$$$$$$$$$$$$$$$
#############################################################
# API.trends_available()
# Returns the locations that Twitter has trending topic information for. The response is an array of “locations” that encode the location’s WOEID (a Yahoo! Where On Earth ID) and some other human-readable information such as a canonical name and country the location belongs in.
# Return type: JSON object
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# f = open('trends_available.txt', 'w+')
# trends_available = api.trends_available()
# f.write(str(trends_available))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#############################################################
# API.trends_place(id[, exclude])
# Returns the top 50 trending topics for a specific WOEID, if trending information is available for it.
# The response is an array of “trend” objects that encode the name of the trending topic, the query parameter that can be used to search for the topic on Twitter Search, and the Twitter Search URL.
# This information is cached for 5 minutes. Requesting more frequently than that will not return any more data, and will count against your rate limit usage.
# The tweet_volume for the last 24 hours is also returned for many trends if this is available.
# Parameters:
# id – The Yahoo! Where On Earth ID of the location to return trending information for. Global information is available by using 1 as the WOEID.
# exclude – Setting this equal to hashtags will remove all hashtags from the trends list.
# Return type:
# JSON object
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# f = open('trends_place.txt', 'w+')
# trends_place = api.trends_place(id = ???)
# f.write(str(trends_place))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#############################################################
# API.trends_closest(lat, long)
# Returns the locations that Twitter has trending topic information for, closest to a specified location.
# The response is an array of “locations” that encode the location’s WOEID and some other human-readable information such as a canonical name and country the location belongs in.
# A WOEID is a Yahoo! Where On Earth ID.
# Parameters:
# lat – If provided with a long parameter the available trend locations will be sorted by distance, nearest to furthest, to the co-ordinate pair. The valid ranges for longitude is -180.0 to +180.0 (West is negative, East is positive) inclusive.
# long – If provided with a lat parameter the available trend locations will be sorted by distance, nearest to furthest, to the co-ordinate pair. The valid ranges for longitude is -180.0 to +180.0 (West is negative, East is positive) inclusive.
# Return type:
# JSON object
# >>>>>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# f = open('trends_closest.txt', 'w+')
# trends_closest = api.trends_closest(lat, long)
# f.write(str(trends_closest))
# f.close()
# >>>>>>>>>>>>>>>>>>>>>>>>>> end >>>>>>>>>>>>>>>>>>>>>>>>>>>>><file_sep>/tmp.py
(Friendship(_api=<tweepy.api.APIobjectat0x7fe3f5e16850>,
followed_by=True,
screen_name=u'dungbk6',
blocked_by=False,
all_replies=False,
muting=False,
live_following=False,
notifications_enabled=False,
_json={
u'notifications_enabled': False,
u'screen_name': u'dungbk6',
u'blocked_by': False,
u'all_replies': False,
u'muting': False,
u'followed_by': True,
u'live_following': False,
u'blocking': False,
u'can_dm': True,
u'marked_spam': False,
u'id_str': u'1176888876473827328',
u'following': True,
u'want_retweets': True,
u'following_requested': False,
u'id': 1176888876473827328,
u'following_received': False
},
id=1176888876473827328,
can_dm=True,
marked_spam=False,
id_str=u'1176888876473827328',
following=True,
want_retweets=True,
following_received=False,
blocking=False,
following_requested=False),
Friendship(_api=<tweepy.api.APIobjectat0x7fe3f5e16850>,
screen_name=u'Snon28281023',
followed_by=True,
_json={
u'screen_name': u'Snon28281023',
u'followed_by': True,
u'id_str': u'1179796116201558017',
u'following': True,
u'following_requested': False,
u'id': 1179796116201558017,
u'following_received': False
},
id_str=u'1179796116201558017',
following=True,
following_received=False,
id=1179796116201558017,
following_requested=False))
|
17e05e6e6d55bfe805b543acd0ad7664cf92cafd
|
[
"Python"
] | 2
|
Python
|
dungbk34/twitter-api-get-data
|
cf62c1c4e6ba846acb87529ec320e2bb4c9a9e39
|
bc688d1a36aab9d06eaf49bf0192f6c4fd637f20
|
refs/heads/master
|
<repo_name>xustella/coordinates<file_sep>/coordinates.go
package coordinates
import "errors"
type Coordinates struct {
longitude, latitude float64
}
//setter methods:
func (c *Coordinates) SetLongitude(lon float64) error {
if lon < -90 || lon > 90 {
return errors.New("Invalid longitude")
}
c.longitude = lon
return nil
}
func (c *Coordinates) SetLatitude(lat float64) error {
if lat < -180 || lat > 180 {
return errors.New("Invalid latitude")
}
c.latitude = lat
return nil
}
//the getter methods:
func (c *Coordinates) Longitude() float64 {
return c.longitude
}
func (c *Coordinates) Latitude() float64 {
return c.latitude
}
|
fd9294341950ffec2b69e124acf643fa6cea6f5f
|
[
"Go"
] | 1
|
Go
|
xustella/coordinates
|
07bc2dfb81c9ccfba6f1689a94307250a3716fea
|
7c5e660c1e398897b3171af9a48215325f8ef5be
|
refs/heads/master
|
<repo_name>kelas-pemrograman-web-si-16/16411029-bella-tugasmobile3<file_sep>/app/src/main/java/com/bella/mobile3bella/inputnilai.java
package com.bella.mobile3bella;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class inputnilai extends AppCompatActivity {
@BindView(R.id.edNpm)
EditText edNpm;
@BindView(R.id.edNama)
EditText edNama;
@BindView(R.id.edTugas)
EditText edTugas;
@BindView(R.id.edQuis)
EditText edQuis;
@BindView(R.id.edUts)
EditText edUts;
@BindView(R.id.edUas)
EditText edUas;
String strNpm, strNama;
double dblTugas, dblQuis, dblUts, dblUas, dblHasil;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inputnilai);
ButterKnife.bind(this);
Intent getData = getIntent();
strNpm = getData.getStringExtra("npm");
strNama= getData.getStringExtra("nama");
edNpm.setText(strNpm);
edNama.setText(strNama);
}
@OnClick(R.id.btnHitung)
void btnHitung(){
dblTugas = Double.parseDouble(edTugas.getText().toString());
dblQuis = Double.parseDouble(edQuis.getText().toString());
dblUts = Double.parseDouble(edUts.getText().toString());
dblUas = Double.parseDouble(edUas.getText().toString());
dblHasil = (dblTugas + dblQuis + dblUts + dblUas) / 4;
//Toast.makeText(getApplicationContext(), String.valueOf(dblHasil),
// Toast.LENGTH_LONG).show();
Intent a = new Intent(inputnilai.this, hasil.class);
a.putExtra("nama", strNama);
a.putExtra("npm", strNpm);
a.putExtra("nilai", String.valueOf(dblHasil));
startActivity(a);
finish();
}
}
<file_sep>/app/src/main/java/com/bella/mobile3bella/hasil.java
package com.bella.mobile3bella;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
public class hasil extends AppCompatActivity {
@BindView(R.id.txtNpm)
TextView txtNpm;
@BindView(R.id.txtNama)
TextView txtNama;
@BindView(R.id.txtNilai)
TextView txtNilai;
@BindView(R.id.txtGrade)
TextView txtGrade;
String strNpm, strNama, strNilai, strGrade;
double dblNilai;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hasil);
ButterKnife.bind(this);
Intent getData = getIntent();
strNpm = getData.getStringExtra("npm");
strNama = getData.getStringExtra("nama");
strNilai = getnData.getStringExtra("nilai");
strGrade = getData.getStringExtra("grade");
dblNilai = Double.parseDouble(strNilai);
txtNpm.setText(strNpm);
txtNama.setText(strNama);
txtNilai.setText(strNilai);
txtGrade.setText(strGrade);
if (dblNilai >=80 && dblNilai <=100) {
txtGrade.setText("A");
} else if (dblNilai >=65 && dblNilai <=79) {
txtGrade.setText("B");
} else if (dblNilai >=60 && dblNilai <=64) {
txtGrade.setText("C");
} else if (dblNilai >=40 && dblNilai <=59) {
txtGrade.setText("D");
} else {
txtGrade.setText("E");
}
}
}
|
24329448385e39ed9baf81792d87489dd92757d0
|
[
"Java"
] | 2
|
Java
|
kelas-pemrograman-web-si-16/16411029-bella-tugasmobile3
|
9052009c1b5213cbe170a15ec20bb55a660b4571
|
0f89345d0326bc4646912d4ded389eeddf60e6dd
|
refs/heads/master
|
<file_sep>/*
* Master.c
*
* Created: 8/14/2020 1:07:35 AM
* Author : <NAME>
*/
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include "UART.h"
#define DDR_SPI DDRB
#define MOSI 3
#define MISO 4
#define SCK 5
#define SS 2
void SPI_MasterInit(void);
void SPI_MasterTransmit(char Data);
void SPI_MasterString(char *str);
char SPI_MasterReceive(void);
int main(void)
{
USART_Init();
SPI_MasterInit();
serialString("hello");
uint8_t data;
while (1)
{
//serialString("inside");
SPI_MasterTransmit('A');
serialString("sent");
_delay_ms(1000);
SPI_MasterTransmit('O');
_delay_ms(1000);
SPI_MasterString("HEYO");
_delay_ms(1000);
data = SPI_MasterReceive();
serialChar(data);
serialString("received");
}
}
void SPI_MasterInit(void)
{
DDR_SPI = (1 << MOSI)|(1 << SCK)|(1 << SS);
SPCR = (1 << SPE)|(1 << MSTR)|(1 <<SPR0);
}
void SPI_MasterTransmit(char Data)
{
PORTB &= ~(1 << SS);
SPDR = Data;
while(!(SPSR &(1 << SPIF)));
PORTB |= (1 << SS);
}
void SPI_MasterString(char *str)
{
while(*str)
{
SPI_MasterTransmit(*str++);
}
_delay_ms(1000);
}
char SPI_MasterReceive(void)
{
PORTB &= ~(1 << SS);
SPDR = 0x00;
while(!(SPSR &(1 << SPIF)));
PORTB |= (1 << SS);
return SPDR;
}
<file_sep>/*
* Master_Interrupts.c
*
* Created: 8/22/2020 8:25:02 PM
* Author : <NAME>
*/
#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include "UART.h"
#define DDR_SPI DDRB
#define MOSI 3
#define MISO 4
#define SCK 5
#define SS 2
#define button 2
#define DDR_BUTTON DDRD
#define PORT_BUTTON PORTD
/*
void SPI_MasterInit(void);
void SPI_MasterTransmit(char Data);
void SPI_MasterString(char *str);
char SPI_MasterReceive(void);
void Interrupt0_Init(void);
*/
void SPI_MasterInit(void)
{
DDR_SPI = (1 << MOSI)|(1 << SCK)|(1 << SS);
SPCR = (1 << SPE)|(1 << MSTR)|(1 <<SPR0);
}
void SPI_MasterTransmit(char Data)
{
PORTB &= ~(1 << SS);
SPDR = Data;
while(!(SPSR &(1 << SPIF)));
PORTB |= (1 << SS);
}
void SPI_MasterString(char *str)
{
while(*str)
{
SPI_MasterTransmit(*str++);
}
_delay_ms(1000);
}
char SPI_MasterReceive(void)
{
PORTB &= ~(1 << SS);
SPDR = 0x00;
while(!(SPSR &(1 << SPIF)));
PORTB |= (1 << SS);
return SPDR;
}
void initInterrupt0(void){
EIMSK |= (1 << INT0);
EICRA |= (1 << ISC00);
sei();
}
ISR(INT0_vect)
{
if(!(PIND & (1 << button)))
{
SPI_MasterTransmit('1');
serialString("sent");
}
else
{
SPI_MasterTransmit('0');
serialString("sent");
}
}
int main(void)
{
initInterrupt0();
USART_Init();
SPI_MasterInit();
DDR_BUTTON |=(1 << button);
PORT_BUTTON |= (1 << button);
serialString("hello");
//uint8_t data;
while (1)
{
serialString("inside");
_delay_ms(1000);
}
}
}
<file_sep># SPI
This repository contains code for SPI Communication between Atmega328p and Atmega2560
<file_sep>/*
* Slave.c
*
* Created: 8/19/2020 10:57:04 PM
* Author : <NAME>
*/
#include <avr/io.h>
#include <util/delay.h>
#include "UART.h"
#define DDR_SPI DDRB
#define MISO 3
#define MOSI 2
#define SCK 1
#define SS 0
void SPI_SlaveInit(void);
char SPI_SlaveReceive(void);
int main(void)
{
USART_Init();
SPI_SlaveInit();
serialString("hello");
uint8_t data;
while (1)
{
//serialString("inside");
data = SPI_SlaveReceive();
//serialString("received");
serialChar(data);
if(data == 'A')
{
PORTB |= (1 << 5);
}
else if(data == 'O')
{
PORTB &= ~(1 << 5);
}
}
}
void SPI_SlaveInit(void)
{
DDR_SPI = (1 << MISO);
SPCR = (1 << SPE);
}
char SPI_SlaveReceive(void)
{
SPDR = 'S';
while(!(SPSR & (1 << SPIF)));
return SPDR;
}
|
4cb9e7c9eab1bcad81c499761266a6c55f3c8574
|
[
"Markdown",
"C"
] | 4
|
C
|
SravaniMalekar/SPI
|
f59f5d4b8ce5b685338257743ef81656c9d57e72
|
8ed52142ab4bf1ab3367167f56663f9a67de9242
|
refs/heads/master
|
<file_sep>
from function_library import * # import functions
units = ['centimeter','meter','inches','Inches','feet','hour'] #the names of the functions that will preform conversion.
flag = True
while flag == True: # Prompts for starting unit
start_unit = raw_input("what is your starting unit: ")
if start_unit in units:
flag = False
else:
print "please enter a vaild unit: "
while flag == False: # Prompts for number to convert
try: # ensures input is a number
number = int(raw_input("\nwhat is your number: "))
flag = True
except:
print 'Enter a valid number: '
while flag == True: # Prompts for unit to convert to
end_unit = raw_input("\nwhat unit do you want to convert to: ")
if end_unit in units:
flag = False
else:
print 'please enter a valid unit: '
final = eval(start_unit + "(number, end_unit)") # stores value of converted number
print str(number) + " " + str(start_unit) + " equals " + str(final) + " " + str(end_unit)
<file_sep>Convert-
========
A simple conversion table
There are three parts of this project.
Model(s), Control, and Veiw.
The Model(s) for this project are the files containing functions to preform the conversions.
The Control will manage the importing, calling, and execution of the application.
My goal is to make a UI using Tkinter; however for now, the Veiw will just run from commandline.
DESIGN:
function template:
def feet(num, endU):
if endU == "inches" or "INCH" or "inch":
num1 = num
num *= 12
return num
elif endU == "centimeters" or "CENTIMETERS":
num1 = num
num /= 0.0328084
return num
elif endU == "Meters" or "meters" or "meter":
num1 = num
num /= 3.28084
return num
else:
pass
<file_sep>
def feet(num, endU):
if endU == "inches" or "INCH" or "inch":
num1 = num
num *= 12
return num
elif endU == "centimeters" or "CENTIMETERS":
num1 = num
num /= 0.0328084
return num
elif endU == "Meters" or "meters" or "meter":
num1 = num
num /= 3.28084
return num
else:
pass
def inches(num, endU):
if endU == "centimeters" or "Centimeters":
num1 = num
num *= 2.54
return num
elif endU == "feet" or "Feet" or "FEET":
num1 = num
num = num / 12.0
return num
elif endU == "meters" or "meter":
num1 = num
num = num / 39.3701
return num
else:
pass
def centimeter(num, endU):
if endU == "INch" or "inches" or "inch":
num1 = num
num = num * 0.393701
return num
elif endU == "feet" or "FEET" or "feet":
num1 = num
num = num * 0.0328084
return num
elif endU == "meters" or "METER" or "meter":
num1 = num
num = num / 100
return num
else:
pass
def meter(num,endU):
if endU == "centimeters" or "centi" or "Centimeters" or "CENTIMETERS":
num1 = num
num *= 100
return num
elif endU == "feet" or "Feet" or "FEET":
num1 = num
num *= 3.28084
print num1, "meter equals", num, " feet"
elif endU == "inches" or " inche":
num1 = num
num *= 39.3701
print num1, " meter equals", num, "inches"
else:
pass
def hour(num, endU):
if endU == "minute" or "Minutes" or "MINUTES":
num1 = num
num *= 60
return num
elif endU == "Seconds" or "seconds":
num1 = num
num *= 3600
return num
else:
pass
|
6b7b2651e8e809dba87ac4148a85a81dc6da94fb
|
[
"Markdown",
"Python"
] | 3
|
Python
|
Acespace/Convert-
|
bc45050ef32c5dd2b0b31d7e2d4692b4c544156f
|
4cd6cce49181e21b82f0cd50ea0a85f4f65545c5
|
refs/heads/master
|
<repo_name>seth7777123/sethmccauleysprint1final<file_sep>/secrets.py
secret shhh
<file_sep>/main.py
import secrets
import requests
def get_data():
all_data = []
for page in range(5):
response = requests.get(f"https://api.data.gov/ed/collegescorecard/v1/schools."
f"json?school.degrees_awarded.predominant="
f"2,3&fields=id,school.name,2013.student.size&api_key={secrets.api_key}&page={page}")
if response.status.status_code != 200:
print("error while getting data")
exit(-1)
page_of_data = response.json()
page_of_school_data = page_of_data['results']
all_data.extend(page_of_school_data)
return all_data
def main():
demo_data = get_data()
print(demo_data)
if __name__ == '__main__':
main()
<file_sep>/README.md
# sethmccauleysprint1final
had alots of trouble trying to do this with java so i decided to try it with python
struggling alot if its not one thing its another just so overwhelmed with everything i
have to do now because im so behind i cant get the flake 8 to run properly and the code wont display unless you click on the file
my java one will be added to you soon its just the gradle and setting that up messed me up its either one or the other sorry its so late
you dont even have to grade it maybe just tell me whats wrong :(
|
65f481e948fb3c45c872bcd19330f036ef2321a2
|
[
"Markdown",
"Python"
] | 3
|
Python
|
seth7777123/sethmccauleysprint1final
|
56372dd297e213b395d78a398028f06d1a92303a
|
e1ecfc91826b0ebe8dbbf76157e8a3115eaaab66
|
refs/heads/main
|
<file_sep>def double(n): #4. pass the data into the function via its PARAMETERS
return n * 2 # 5. return
userstring = input("Number please:")# 1. request user input
usernum = int(userstring) # 2. convert to an integer
print(double(usernum)) # 3, call the function with an argument
<file_sep>def introduce(person1,person2):
print("Hello "+person1+", this is "+person2+".");
p1 = input("Enter a name to greet: ");
p2 = input("Enter a name to introduce: ");
introduce(p1,p2);
<file_sep>def factorial(n):
return n + Sum;
num = input("Number please: ");
num = int(num);
Sum = num;
for x in range(0,num):
--x;
if(x > 0):
Sum = Sum*x;
Sum = Sum/2;
print(factorial(Sum));
|
b3d9789b0babf9c662add1431a5352cfd2aff65e
|
[
"Python"
] | 3
|
Python
|
Kevinp1402/lab-09-functions
|
f7c8aa504f71f3a360331ec65570a6b669c51b7b
|
e3d41295e09667987ac2e296d4b9eda638ac2a09
|
refs/heads/master
|
<repo_name>mathieuferreira/collect-web-service<file_sep>/src/AppBundle/Extensions/Controller/Controller.php
<?php
/**
* Created by PhpStorm.
* User: mathieuferreira
* Date: 16/04/17
* Time: 19:43
*/
namespace AppBundle\Extensions\Controller;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormError;
class Controller extends \Symfony\Bundle\FrameworkBundle\Controller\Controller{
#region Const
#endregion
#region Public Properties
#endregion
#region Protected Properties
#endregion
#region Private Properties
#endregion
#region Magic methods
#endregion
#region Getters/Setters
/**
* @return \Doctrine\Common\Persistence\ObjectManager|object
*/
public function getMongoManager(){
if (!$this->container->has('doctrine_mongodb')) {
throw new \LogicException('The DoctrineMongoDB is not registered in your application.');
}
return $this->container->get('doctrine_mongodb')->getManager();
}
public function json($data, $status = 200, $headers = array(), $context = array()){
if($data instanceof Form){
$errors = $data->getErrors(true);
$data = [
's' => count($errors) > 0
];
if(count($errors) > 0){
/** @var FormError $error */
foreach($errors as $error){
$data['e'][] = $error->getMessage();
}
}
}
return parent::json($data, $status, $headers, $context);
}
#endregion
#region Public methods
#endregion
#region Protected methods
#endregion
#region Private methods
#endregion
}<file_sep>/src/AppBundle/Controller/DefaultController.php
<?php
namespace AppBundle\Controller;
use AppBundle\Document\Data;
use AppBundle\Type\CollectType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Form\FormError;
use AppBundle\Extensions\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\Count;
use Symfony\Component\VarDumper\VarDumper;
class DefaultController extends Controller
{
/**
* @Route("/collect", name="collect")
* @Method({"GET", "POST"})
*/
public function collectAction(Request $request)
{
$form = $this->get('form.factory')->createNamed('', CollectionType::class, null, [
'method' => $request->getMethod(),
'entry_type'=> CollectType::class,
'allow_add' => true,
'constraints' => [
new Count(['min' => 1])
],
'csrf_protection' => false
]);
$form->submit($request->getMethod() === 'GET' ? [$request->query->all()] : json_decode($request->getContent(), true), true);
if($form->isValid()){
$mongoManager = $this->getMongoManager();
foreach($form as $child){
$mongoManager->persist($child->getData());
}
$mongoManager->flush();
}
return $this->json($form);
}
}
<file_sep>/README.md
Collect Web service
=========
A symfony Rest API to collect datas.
=========
Path : /collect
###### Return Examples:
```json
{"s":false,"e":["Parameter t is missing", "User wui not found"]}
```
```json
{"s": true}
```
| Parameter Name | Parameter format | Example | Description | Mandatory |
| --- | --- | --- | --- | --- |
| Success | s | s=true | Boolean describing if request was successfully executed or not | Yes |
| Errors | e | e=["Parameters are missing"] | Array of errors | Yes if not successfull |
<file_sep>/tests/AppBundle/Controller/DefaultControllerTest.php
<?php
namespace Tests\AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use AppBundle\Document\User;
class DefaultControllerTest extends WebTestCase
{
public function testCollect()
{
$client = static::createClient();
$user = $client->getContainer()->get('doctrine_mongodb')->getManager()->getRepository(User::class)->findOneBy(['userId' => 'test-wizbii']);
if($user === NULL){
$user = new User();
$user->setUserId('test-wizbii');
$user->setFirstName('Test');
$user->setLastName('Wizbii');
$user->setEmail('<EMAIL>');
$client->getContainer()->get('doctrine_mongodb')->getManager()->persist($user);
$client->getContainer()->get('doctrine_mongodb')->getManager()->flush();
}
$client->request('GET', '/');
$this->assertTrue($client->getResponse()->isNotFound());
$this->assertTrue(
$client->getResponse()->headers->contains(
'Content-Type',
'application/json'
),
'the "Content-Type" header is "application/json"' // optional message shown on failure
);
$this->assertContains('"s":false', $client->getResponse()->getContent());
// Missing datas
$this->executeTestForData($client, ['v'=>1], false);
// unknown userId
$this->executeTestForData($client, ['v'=>1,'t'=>'pageview', 'wct'=>'visitor', 'wui'=>'1234', 'wuui'=>3, 'tid'=>'UA-1234-Y', 'ds'=>'web'], false);
// Bad format tid
$this->executeTestForData($client, ['v'=>1,'t'=>'pageview', 'wct'=>'visitor', 'wui'=>$user->getUserId(), 'wuui'=>3, 'tid'=>'UA-1234', 'ds'=>'web'], false);
// Bad version
$this->executeTestForData($client, ['v'=>2,'t'=>'pageview', 'wct'=>'visitor', 'wui'=>$user->getUserId(), 'wuui'=>3, 'tid'=>'UA-1234-Y', 'ds'=>'web'], false);
// Missing data for ds-apps
$this->executeTestForData($client, ['v'=>1,'t'=>'pageview', 'wct'=>'visitor', 'wui'=>$user->getUserId(), 'wuui'=>3, 'tid'=>'UA-1234-Y', 'ds'=>'apps'], false);
// Missing data for t-event
$this->executeTestForData($client, ['v'=>1,'t'=>'event', 'wct'=>'visitor', 'wui'=>$user->getUserId(), 'wuui'=>3, 'tid'=>'UA-1234-Y', 'ds'=>'web'], false);
// Success
$this->executeTestForData($client, ['v'=>1,'t'=>'pageview', 'wct'=>'visitor', 'wui'=>$user->getUserId(), 'wuui'=>3, 'tid'=>'UA-1234-Y', 'ds'=>'web'], true);
}
private function executeTestForData($client, $data, $success){
$client->request('GET', '/collect', $data);
$this->checkSuccess($client, $success);
if($success)
sleep(1);
$client->request('POST', '/collect', [], [], [], json_encode([$data]));
$this->checkSuccess($client, $success);
if($success)
sleep(1);
}
private function checkSuccess($client, $success){
$this->assertEquals(
200,
$client->getResponse()->getStatusCode()
);
$this->assertTrue(
$client->getResponse()->headers->contains(
'Content-Type',
'application/json'
),
'the "Content-Type" header is "application/json"' // optional message shown on failure
);
$this->assertContains('"s"', $client->getResponse()->getContent());
$json = json_decode($client->getResponse()->getContent(), true);
if($success){
$this->assertTrue($json['s'], "Success return true");
}else{
$this->assertFalse($json['s'], "Success return false");
$this->assertGreaterThan(
0,
count($json['e']),
"There are errors in json"
);
}
}
}
<file_sep>/src/AppBundle/Type/Validator/UserExists.php
<?php
/**
* Created by PhpStorm.
* User: mathieuferreira
* Date: 16/04/17
* Time: 20:32
*/
namespace AppBundle\Type\Validator;
use Symfony\Component\Validator\Constraint;
class UserExists extends Constraint{
#region Const
#endregion
#region Public Properties
public $message = 'Unknown user Id.';
#endregion
#region Protected Properties
#endregion
#region Private Properties
#endregion
#region Magic methods
#endregion
#region Getters/Setters
#endregion
#region Public methods
#endregion
#region Protected methods
#endregion
#region Private methods
#endregion
}<file_sep>/src/AppBundle/Document/User.php
<?php
/**
* Created by PhpStorm.
* User: mathieuferreira
* Date: 16/04/17
* Time: 15:15
*/
namespace AppBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* @MongoDB\Document
*/
class User {
#region Const
#endregion
#region Public Properties
#endregion
#region Protected Properties
/**
* @MongoDB\Id
*/
protected $id;
/**
* @MongoDB\Field(type="string")
*/
protected $userId;
/**
* @MongoDB\Field(type="string")
*/
protected $firstName;
/**
* @MongoDB\Field(type="string")
*/
protected $lastName;
/**
* @MongoDB\Field(type="string")
*/
protected $email;
#endregion
#region Private Properties
#endregion
#region Magic methods
#endregion
#region Getters/Setters
/** @return mixed */
public function getId()
{
return $this->id;
}
/** @return mixed */
public function getUserId()
{
return $this->userId;
}
/**
* @param mixed $userId
* @return User
*/
public function setUserId($userId)
{
$this->userId = $userId;
return $this;
}
/** @return mixed */
public function getFirstName()
{
return $this->firstName;
}
/**
* @param mixed $firstName
* @return User
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
/** @return mixed */
public function getLastName()
{
return $this->lastName;
}
/**
* @param mixed $lastName
* @return User
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/** @return mixed */
public function getEmail()
{
return $this->email;
}
/**
* @param mixed $email
* @return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
#endregion
#region Public methods
#endregion
#region Protected methods
#endregion
#region Private methods
#endregion
}<file_sep>/src/AppBundle/Type/Validator/UserExistsValidator.php
<?php
/**
* Created by PhpStorm.
* User: mathieuferreira
* Date: 16/04/17
* Time: 20:37
*/
namespace AppBundle\Type\Validator;
use AppBundle\Document\User;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Doctrine\Common\Persistence\AbstractManagerRegistry;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\VarDumper\VarDumper;
class UserExistsValidator extends ConstraintValidator{
#region Const
#endregion
#region Public Properties
#endregion
#region Protected Properties
#endregion
#region Private Properties
/** @var AbstractmanagerRegistry */
private $mongoDoctrine;
#endregion
#region Magic methods
public function __construct(AbstractmanagerRegistry $mongoDoctrine){
$this->mongoDoctrine = $mongoDoctrine;
}
#endregion
#region Getters/Setters
#endregion
#region Public methods
/**
* Checks if the passed value is valid.
*
* @param mixed $value The value that should be validated
* @param Constraint $constraint The constraint for the validation
*/
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof UserExists) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\UserExists');
}
$user = $this->mongoDoctrine->getManager()->getRepository(User::class)->findOneBy(['userId' => $value]);
if ($user === NULL){
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->addViolation();
}
}
#endregion
#region Protected methods
#endregion
#region Private methods
#endregion
}<file_sep>/src/AppBundle/Document/Data.php
<?php
/**
* Created by PhpStorm.
* User: mathieuferreira
* Date: 16/04/17
* Time: 15:16
*/
namespace AppBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* @MongoDB\Document
*/
class Data {
#region Const
const HITTYPE_PAGEVIEW = 'pageview';
const HITTYPE_SCREENVIEW = 'screenview';
const HITTYPE_EVENT = 'event';
const CREATORTYPE_PROFILE = 'profile';
const CREATORTYPE_RECRUITER = 'recruiter';
const CREATORTYPE_VISITOR = 'visitor';
const CREATORTYPE_EMPLOYEE = 'wizbii_employee';
const DATASOURCE_WEB = 'web';
const DATASOURCE_APPS = 'apps';
const DATASOURCE_BACKEND = 'backend';
#endregion
#region Public Properties
public static $hitTypes = [
self::HITTYPE_PAGEVIEW,
self::HITTYPE_SCREENVIEW,
self::HITTYPE_EVENT,
];
public static $creatorTypes = [
self::CREATORTYPE_PROFILE,
self::CREATORTYPE_RECRUITER,
self::CREATORTYPE_VISITOR,
self::CREATORTYPE_EMPLOYEE,
];
public static $dataSources = [
self::DATASOURCE_WEB,
self::DATASOURCE_APPS,
self::DATASOURCE_BACKEND,
];
#endregion
#region Protected Properties
/**
* @MongoDB\Id
*/
protected $id;
/**
* @MongoDB\Field(type="string")
*/
protected $version;
/**
* @MongoDB\Field(type="string")
*/
protected $hitType;
/**
* @MongoDB\Field(type="string")
*/
protected $documentLocation;
/**
* @MongoDB\Field(type="string")
*/
protected $documentReferer;
/**
* @MongoDB\Field(type="string")
*/
protected $creatorType;
/**
* @MongoDB\Field(type="string")
*/
protected $userId;
/**
* @MongoDB\Field(type="string")
*/
protected $uniqUserId;
/**
* @MongoDB\Field(type="string")
*/
protected $eventCategory;
/**
* @MongoDB\Field(type="string")
*/
protected $eventAction;
/**
* @MongoDB\Field(type="string")
*/
protected $eventLabel;
/**
* @MongoDB\Field(type="string")
*/
protected $eventValue;
/**
* @MongoDB\Field(type="string")
*/
protected $trackingId;
/**
* @MongoDB\Field(type="string")
*/
protected $dataSource;
/**
* @MongoDB\Field(type="string")
*/
protected $campaignName;
/**
* @MongoDB\Field(type="string")
*/
protected $campaignSource;
/**
* @MongoDB\Field(type="string")
*/
protected $campaignMedium;
/**
* @MongoDB\Field(type="string")
*/
protected $campaignKeyword;
/**
* @MongoDB\Field(type="string")
*/
protected $campaignContent;
/**
* @MongoDB\Field(type="string")
*/
protected $screenName;
/**
* @MongoDB\Field(type="string")
*/
protected $applicationName;
/**
* @MongoDB\Field(type="string")
*/
protected $applicationVersion;
/**
* @MongoDB\Field(type="timestamp")
*/
protected $collectDate;
#endregion
#region Private Properties
#endregion
#region Magic methods
#endregion
#region Getters/Setters
/** @return mixed */
public function getId()
{
return $this->id;
}
/** @return mixed */
public function getVersion()
{
return $this->version;
}
/**
* @param mixed $version
* @return Data
*/
public function setVersion($version)
{
$this->version = $version;
return $this;
}
/** @return mixed */
public function getHitType()
{
return $this->hitType;
}
/**
* @param mixed $hitType
* @return Data
*/
public function setHitType($hitType)
{
$this->hitType = $hitType;
return $this;
}
/** @return mixed */
public function getDocumentLocation()
{
return $this->documentLocation;
}
/**
* @param mixed $documentLocation
* @return Data
*/
public function setDocumentLocation($documentLocation)
{
$this->documentLocation = $documentLocation;
return $this;
}
/** @return mixed */
public function getDocumentReferer()
{
return $this->documentReferer;
}
/**
* @param mixed $documentReferer
* @return Data
*/
public function setDocumentReferer($documentReferer)
{
$this->documentReferer = $documentReferer;
return $this;
}
/** @return mixed */
public function getCreatorType()
{
return $this->creatorType;
}
/**
* @param mixed $creatorType
* @return Data
*/
public function setCreatorType($creatorType)
{
$this->creatorType = $creatorType;
return $this;
}
/** @return mixed */
public function getUserId()
{
return $this->userId;
}
/**
* @param mixed $userId
* @return Data
*/
public function setUserId($userId)
{
$this->userId = $userId;
return $this;
}
/** @return mixed */
public function getUniqUserId()
{
return $this->uniqUserId;
}
/**
* @param mixed $uniqUserId
* @return Data
*/
public function setUniqUserId($uniqUserId)
{
$this->uniqUserId = $uniqUserId;
return $this;
}
/** @return mixed */
public function getEventCategory()
{
return $this->eventCategory;
}
/**
* @param mixed $eventCategory
* @return Data
*/
public function setEventCategory($eventCategory)
{
$this->eventCategory = $eventCategory;
return $this;
}
/** @return mixed */
public function getEventAction()
{
return $this->eventAction;
}
/**
* @param mixed $eventAction
* @return Data
*/
public function setEventAction($eventAction)
{
$this->eventAction = $eventAction;
return $this;
}
/** @return mixed */
public function getEventLabel()
{
return $this->eventLabel;
}
/**
* @param mixed $eventLabel
* @return Data
*/
public function setEventLabel($eventLabel)
{
$this->eventLabel = $eventLabel;
return $this;
}
/** @return mixed */
public function getEventValue()
{
return $this->eventValue;
}
/**
* @param mixed $eventValue
* @return Data
*/
public function setEventValue($eventValue)
{
$this->eventValue = $eventValue;
return $this;
}
/** @return mixed */
public function getTrackingId()
{
return $this->trackingId;
}
/**
* @param mixed $trackingId
* @return Data
*/
public function setTrackingId($trackingId)
{
$this->trackingId = $trackingId;
return $this;
}
/** @return mixed */
public function getDataSource()
{
return $this->dataSource;
}
/**
* @param mixed $dataSource
* @return Data
*/
public function setDataSource($dataSource)
{
$this->dataSource = $dataSource;
return $this;
}
/** @return mixed */
public function getCampaignName()
{
return $this->campaignName;
}
/**
* @param mixed $campaignName
* @return Data
*/
public function setCampaignName($campaignName)
{
$this->campaignName = $campaignName;
return $this;
}
/** @return mixed */
public function getCampaignSource()
{
return $this->campaignSource;
}
/**
* @param mixed $campaignSource
* @return Data
*/
public function setCampaignSource($campaignSource)
{
$this->campaignSource = $campaignSource;
return $this;
}
/** @return mixed */
public function getCampaignMedium()
{
return $this->campaignMedium;
}
/**
* @param mixed $campaignMedium
* @return Data
*/
public function setCampaignMedium($campaignMedium)
{
$this->campaignMedium = $campaignMedium;
return $this;
}
/** @return mixed */
public function getCampaignKeyword()
{
return $this->campaignKeyword;
}
/**
* @param mixed $campaignKeyword
* @return Data
*/
public function setCampaignKeyword($campaignKeyword)
{
$this->campaignKeyword = $campaignKeyword;
return $this;
}
/** @return mixed */
public function getCampaignContent()
{
return $this->campaignContent;
}
/**
* @param mixed $campaignContent
* @return Data
*/
public function setCampaignContent($campaignContent)
{
$this->campaignContent = $campaignContent;
return $this;
}
/** @return mixed */
public function getScreenName()
{
return $this->screenName;
}
/**
* @param mixed $screenName
* @return Data
*/
public function setScreenName($screenName)
{
$this->screenName = $screenName;
return $this;
}
/** @return mixed */
public function getApplicationName()
{
return $this->applicationName;
}
/**
* @param mixed $applicationName
* @return Data
*/
public function setApplicationName($applicationName)
{
$this->applicationName = $applicationName;
return $this;
}
/** @return mixed */
public function getApplicationVersion()
{
return $this->applicationVersion;
}
/**
* @param mixed $applicationVersion
* @return Data
*/
public function setApplicationVersion($applicationVersion)
{
$this->applicationVersion = $applicationVersion;
return $this;
}
/** @return mixed */
public function getCollectDate()
{
return $this->collectDate;
}
/**
* @param mixed $collectDate
* @return Data
*/
public function setCollectDate($collectDate)
{
$this->collectDate = $collectDate;
return $this;
}
/**
* @return int
*/
public function getQueueTime(){
if($this->collectDate === NULL)
return 0;
return time() - $this->collectDate;
}
/**
* @param int $queueTime
* @return Data
*/
public function setQueueTime($queueTime){
$this->collectDate = time() - $queueTime;
return $this;
}
#endregion
#region Public methods
#endregion
#region Protected methods
#endregion
#region Private methods
#endregion
}<file_sep>/src/AppBundle/Type/CollectType.php
<?php
namespace AppBundle\Type;
use AppBundle\Document\Data;
use AppBundle\Type\Validator\UserExists;
use Doctrine\Common\Persistence\AbstractManagerRegistry;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\GreaterThan;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Choice;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Constraints\Url;
use Symfony\Component\Validator\Constraints\Type;
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\VarDumper\VarDumper;
use Doctrine\DBAL\Query\QueryBuilder;
use Doctrine\MongoDB\Query\Builder;
/**
* Created by PhpStorm.
* User: mathieuferreira
* Date: 16/04/17
* Time: 14:14
*/
class CollectType extends AbstractType {
#region Const
#endregion
#region Public Properties
#endregion
#region Protected Properties
#endregion
#region Private Properties
/** @var int */
private $timeout;
/** @var AbstractManagerRegistry */
private $mongoDoctrine;
#endregion
#region Magic methods
public function __construct(AbstractManagerRegistry $mongoDoctrine, $timeout){
$this->timeout = $timeout;
$this->mongoDoctrine = $mongoDoctrine;
}
#endregion
#region Getters/Setters
#endregion
#region Public methods
public function buildForm(FormBuilderInterface $builder, array $options){
$builder
->add('v', TextType::class, [
'property_path' => 'version',
'constraints' => [
new NotBlank(['message' => 'Version (v) cannot be blank.']),
new Choice(['choices' => ['1'], 'message' => 'Version (v) not supported.'])
]
])
->add('t', TextType::class, [
'property_path' => 'hitType',
'constraints' => [
new NotBlank(['message' => 'Hit type (t) cannot be blank.']),
new Choice([
'choices' => Data::$hitTypes,
'message' => sprintf('Hit type (t) not supported. Supported values : %s', implode(',', Data::$hitTypes))
])
]
])
->add('dl', TextType::class, [
'property_path' => 'documentLocation',
'constraints' => [
//new Url(['message' => 'Document location (dl) has to be a valid Url.'])
]
])
->add('dr', TextType::class, [
'property_path' => 'documentReferer',
'constraints' => [
//new Url(['message' => 'Document referer (dr) has to be a valid Url.'])
]
])
->add('wct', TextType::class, [
'property_path' => 'creatorType',
'constraints' => [
new NotBlank(['message' => 'Wizbii creator type (wct) cannot be blank.']),
new Choice([
'choices' => Data::$creatorTypes,
'message' => sprintf('Wizbii creator type (wct) not supported. Supported values : %s', implode(',', Data::$creatorTypes))
])
]
])
->add('wui', TextType::class, [
'property_path' => 'userId',
'constraints' => [
new NotBlank(['message' => 'Wizbii User id (wui) cannot be blank.']),
new UserExists()
]
])
->add('wuui', TextType::class, [
'property_path' => 'uniqUserId',
'constraints' => [
new NotBlank(['message' => 'Wizbii Uniq User id (wuui) cannot be blank.'])
]
])
->add('ec', TextType::class, [
'property_path' => 'eventCategory',
'constraints' => [
new NotBlank(['groups' => ['t-event'], 'message' => 'Event category (ec) cannot be blank.'])
]
])
->add('ea', TextType::class, [
'property_path' => 'eventAction',
'constraints' => [
new NotBlank(['groups' => ['t-event'], 'message' => 'Event action (ea) cannot be blank.'])
]
])
->add('el', TextType::class, ['property_path' => 'eventLabel'])
->add('ev', IntegerType::class, [
'property_path' => 'eventValue',
'constraints' => [
new Type(['type' => 'integer', 'message' => 'Event value (ev) has to be an integer.']),
new GreaterThan(['value' => 0, 'message' => 'Event value (ev) has to be a positive integer.'])
],
'data' => 1
])
->add('tid', TextType::class, [
'property_path' => 'trackingId',
'constraints' => [
new NotBlank(['message' => 'Tracking id (tid) cannot be blank.']),
new Regex(['pattern' => '/^UA\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{1}$/', 'message' => 'Tracking id (tid) has to be formatted like UA-XXXX-Y.'])
]
])
->add('ds', TextType::class, [
'property_path' => 'dataSource',
'constraints' => [
new NotBlank(['message' => 'Data source (ds) cannot be blank.']),
new Choice([
'choices' => Data::$dataSources,
'message' => sprintf('Data source (ds) not supported. Supported values : %s', implode(',', Data::$dataSources))
])
]
])
->add('cn', TextType::class, ['property_path' => 'campaignName'])
->add('cs', TextType::class, ['property_path' => 'campaignSource'])
->add('cm', TextType::class, ['property_path' => 'campaignMedium'])
->add('ck', TextType::class, ['property_path' => 'campaignKeyword'])
->add('cc', TextType::class, ['property_path' => 'campaignContent'])
->add('sn', TextType::class, [
'property_path' => 'screenName',
'constraints' => [
new NotBlank(['groups' => ['t-screenview'], 'message' => 'Screen name (sn) cannot be blank.'])
]
])
->add('an', TextType::class, [
'property_path' => 'applicationName',
'constraints' => [
new NotBlank(['groups' => ['ds-apps'], 'message' => 'Application name (an) cannot be blank.'])
]
])
->add('av', TextType::class, ['property_path' => 'applicationVersion'])
->add('qt', IntegerType::class, [
'property_path' => 'queueTime',
'constraints' => [
new Type(['type' => 'integer', 'message' => 'Queue time (qt) has to be an integer.']),
new Range([
'min' => 0,
'max' => $this->timeout,
'minMessage' => 'Queue time (qt) has to be greater than 0.',
'maxMessage' => sprintf('Queue time (qt) has to be lesser than %d.', $this->timeout)
])
],
'data' => 0
]);
}
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver->setDefault('data_class', Data::class);
$resolver->setDefault('validation_groups', function(FormInterface $form){
return [
'Default',
't-' . $form->get('t')->getData(),
'ds-' . $form->get('ds')->getData()
];
});
$resolver->setNormalizer('constraints', function(Options $options, $value){
return array_merge(
$value,
[
new Callback(['callback' => function($value, ExecutionContextInterface $context){
/** @var Data $value */
/** @var Builder $queryBuilder */
$queryBuilder = $this->mongoDoctrine->getManager()->getRepository(Data::class)->createQueryBuilder('d');
$queryBuilder->addAnd(
$queryBuilder->expr()->addAnd(
$queryBuilder->expr()->field('userId')->equals($value->getUserId()),
$queryBuilder->expr()->field('hitType')->equals($value->getHitType()),
$queryBuilder->expr()->field('collectDate')->gte(time() - 1)
)
);
$data = $queryBuilder->getQuery()->getSingleResult();
if ($data !== NULL){
$context->buildViolation('An event cannot occurred more than one time a second')
->addViolation();
}
}])
]
);
});
}
#endregion
#region Protected methods
#endregion
#region Private methods
#endregion
}
|
4f9c22b3cf033a06e5702b12e9bc2ce2edebf2f9
|
[
"Markdown",
"PHP"
] | 9
|
PHP
|
mathieuferreira/collect-web-service
|
c6177ef90a659500f182f293cd389b256cc9b550
|
bebd33972f00518c645c1eda93e2728f5770fc66
|
refs/heads/master
|
<repo_name>natassm/java-VolleyExample<file_sep>/app/src/main/java/com/example/volleyexample/fragment/MusicFragment.java
package com.example.volleyexample.fragment;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.example.volleyexample.Music;
import com.example.volleyexample.R;
import com.nostra13.universalimageloader.core.ImageLoader;
public class MusicFragment extends Fragment {
private ImageView imageView;
private TextView artistName, songTitle;
private Button btnPlay, btnPrev, btnNext;
private SeekBar seekBar;
public static Bundle passingData(Music music) {
Bundle bundle = new Bundle();
bundle.putParcelable("data", music);
return bundle;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_music, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
loadView(view);
loadData();
}
private void loadData() {
Music music = getArguments().getParcelable("data");
artistName.setText(music.getArtistName());
songTitle.setText(music.getName());
// ImageLoader imageLoader = ImageLoader.getInstance();
// imageLoader.displayImage(music.getUrl(), imageView);
}
private void loadView(View view) {
imageView = view.findViewById(R.id.imageView);
artistName = view.findViewById(R.id.artistName);
songTitle = view.findViewById(R.id.songTitle);
btnNext = view.findViewById(R.id.btnNext);
btnPlay = view.findViewById(R.id.btnPlay);
btnPrev = view.findViewById(R.id.btnPrev);
seekBar = view.findViewById(R.id.seekBar);
}
}
<file_sep>/app/src/main/java/com/example/volleyexample/adapter/MusicAdapter.java
package com.example.volleyexample.adapter;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import com.example.volleyexample.Music;
import com.example.volleyexample.fragment.MusicFragment;
import java.util.ArrayList;
import java.util.List;
public class MusicAdapter extends FragmentStatePagerAdapter {
private List<Music> musicList = new ArrayList<>();
public MusicAdapter(FragmentManager fm, List<Music> musicList) {
super(fm);
this.musicList = musicList;
}
@Override
public Fragment getItem(int position) {
MusicFragment musicFragment = new MusicFragment();
musicFragment.setArguments(MusicFragment.passingData(musicList.get(position)));
return musicFragment;
}
@Override
public int getCount() {
return musicList.size();
}
}
<file_sep>/app/src/main/java/com/example/volleyexample/MainActivity.java
package com.example.volleyexample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewParent;
import android.widget.Button;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.volleyexample.adapter.MusicAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getName();
private RequestQueue requestQueue;
private StringRequest stringRequest;
private String url = "http://www.mocky.io/v2/5d21a0332f00002101c462d2";
private ViewPager pager;
private Button btn;
private ArrayList<Music> musicList = new ArrayList<>();
private MusicAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = findViewById(R.id.pager);
// btn = findViewById(R.id.btn1);
//
// btn.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// sendAndRequestResponse();
// }
// });
setUpAdapter();
sendAndRequestResponse();
}
private void setUpAdapter() {
adapter = new MusicAdapter(getSupportFragmentManager(), musicList);
pager.setAdapter(adapter);
}
private void sendAndRequestResponse(){
requestQueue = Volley.newRequestQueue(this);
stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject jsonObject1 = jsonObject.getJSONObject("feed");
parseResponseFromJson(jsonObject1);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, "Error :" + error.toString());
}
});
requestQueue.add(stringRequest);
}
private void parseResponseFromJson(JSONObject jsonResponse) throws JSONException {
JSONArray jsonResults = jsonResponse.getJSONArray("results");
for (int i = 0; i < jsonResults.length(); i++) {
JSONObject r = jsonResults.getJSONObject(i);
String artistName = r.getString("artistName");
String id = r.getString("id");
String name = r.getString("name");
String url = r.getString("artworkUrl100");
Music music = new Music(artistName, id, name, url);
musicList.add(music);
}
}
}
|
adacd97eab89ea09bb5f4b361175ab4eb421426c
|
[
"Java"
] | 3
|
Java
|
natassm/java-VolleyExample
|
f0eb6b2397c2f79ac70b873ba9c6b572214a2be9
|
a98bfde05e39ec712273f43f9000e2d4bf056e94
|
refs/heads/master
|
<file_sep>package constants;
public class Constant {
public static class TimeoutVariable{
public static final int IMPLICIT_WAIT = 4;
public static final int EXPLICIT_WAIT = 10;
}
public static class Urls{
public static final String REALT_HOME_PAGE = "https://realt.by/";
}
}
<file_sep>package pages.realt_home;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import pages.base.BasePage;
public class RealtHomePage extends BasePage {
public RealtHomePage(WebDriver driver) {
super(driver);
}
private final By countRooms = By.id("rooms");
private final By option2Rooms = By.xpath("//select[@id = 'rooms']//option[3]");
private final By findBtn = By.xpath("//*[@class = 'common-search-submit btn btn-primary']");
public RealtHomePage enterCountRooms() {
driver.findElement(countRooms).click();
driver.findElement(option2Rooms).click();
return this;
}
public RealtHomePage clickToFind(){
WebElement btnFind = driver.findElement(findBtn);
waitElementIsVisible(btnFind).click();
return this;
}
}
<file_sep>package tests.base;
import common.CommonActions;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import pages.base.BasePage;
import pages.listing.RealtListingPage;
import pages.realt_home.RealtHomePage;
import static common.Configurations.CLEAR_COOKIES_AND_STORAGE;
import static common.Configurations.HOLD_BROWSER_OPEN;
public class BaseTest {
protected WebDriver driver = CommonActions.createDriver();
protected BasePage basePage = new BasePage(driver);
protected RealtHomePage realtHomePage = new RealtHomePage(driver);
protected RealtListingPage realtListingPage = new RealtListingPage(driver);
@AfterTest
public void clearCookiesAndLocalStorage(){
if(CLEAR_COOKIES_AND_STORAGE){
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
driver.manage().deleteAllCookies();
javascriptExecutor.executeScript("window.sessionStorage.clear()");
}
}
@AfterSuite(alwaysRun = true)
public void close(){
if(HOLD_BROWSER_OPEN){
driver.quit();
}
}
}
<file_sep>[SuiteResult context=D:/PageObjectTestNGFramework]
|
8ef95e921d4b2c83eae97fbc75313a97eda7e6ee
|
[
"Java",
"INI"
] | 4
|
Java
|
vsilver/PageObjectTestNGFramework
|
e7bc060dcac120822e3b72937dc276e627684476
|
65ca081f1d7ab191e3bc4c98c54be0c8c3ba716b
|
refs/heads/master
|
<repo_name>elewis33/ng-infinite-scroll<file_sep>/scroll-controller.js
if (Meteor.isClient) {
var module = angular.module('scroll-demo', ['angular-meteor', 'infinite-scroll']);
module.controller('ngInfiniteScrollCtrl', ['$scope', '$meteor',
function($scope, $meteor) {
var page = 20;
$meteor.subscribe('images', {
skip: 0,
limit: 2 * page
});
$scope.images = $meteor.collection(function() {
return Images.find();
});
$scope.loadMore = function() {
var len = $scope.images.length;
$meteor.subscribe('images', {
skip: len,
limit: page
});
};
}]);
}
<file_sep>/README.md
# ng-infinite-scroll
Forked this so I can learn more about how to implement infinite scrolling with Angular/Meteor. Please refer to the original repo and author if you have quesitons.
|
bae78526d899d93404dfe7056beb4f261e937afb
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
elewis33/ng-infinite-scroll
|
b54e19d1bfedc398365d8fd200659c1f0deb6337
|
c8555cc3d4e9d1902e057837bf07013d09a1c8c9
|
refs/heads/master
|
<file_sep>import React from 'react';
import {
View,
Text,
FlatList,
} from 'react-native';
import styles from '../styles/SingleRecipeStyle';
const UsedIngredientsFromList = ({ recipe }) => {
formatIngredientName = ingredient => {
let formatted = ingredient[0].toUpperCase() + ingredient.slice(1);
return formatted;
};
return (
<View>
<Text style={styles.recipeName}>
Total Used Ingredient(s) from Your List: {recipe.usedIngredientCount}{' '}
</Text>
<FlatList
data={recipe.usedIngredients}
keyExtractor={(item, index) => 'key' + index}
renderItem={({ item, index }) => {
return (
<View style={styles.container}>
<View style={{ flexDirection: 'row' }}>
<Text style={{ fontWeight: 'bold', fontSize: 16 }}>
{index + 1}. {formatIngredientName(item.name)}
</Text>
</View>
<View>
<Text style={styles.recipeIngredientName}>
{item.originalString}
</Text>
</View>
</View>
);
}}
/>
</View>
)
}
export default UsedIngredientsFromList;<file_sep>import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
searchBar: {
backgroundColor: '#cccccc',
height: 50,
borderRadius: 5,
marginHorizontal: 15,
marginTop: 15,
flexDirection: 'row',
marginBottom: 5,
width: 345
},
input: {
flex: 1,
fontSize: 18
},
addButton: {
marginTop: 2,
width: 60,
justifyContent: 'center',
marginHorizontal: 7,
alignSelf: 'center'
},
buttonText: {
fontSize: 14,
fontWeight: 'bold',
color: '#F2C04C',
},
})
export default styles;<file_sep>import db from '../api/db/database';
// ACTION TYPES
export const GET_PAST_RECIPES_FROM_STORE = 'GET_PAST_RECIPES_FROM_STORE';
export const CLEAR_PAST_RECIPES_FROM_STORE = 'CLEAR_PAST_RECIPES_FROM_STORE';
export const GOT_PAST_RECIPES = 'GOT_PAST_RECIPES';
export const ADD_TO_PAST_RECIPES = 'ADD_TO_PAST_RECIPES';
// ACTION CREATORS
export const getPastRecipesFromStore = () => {
return {
type: GET_PAST_RECIPES_FROM_STORE,
};
};
export const clearPastRecipesFromStore = () => {
return {
type: CLEAR_PAST_RECIPES_FROM_STORE,
};
};
export const getPastRecipes = pastRecipes => {
return {
type: GOT_PAST_RECIPES,
pastRecipes,
};
};
export const addToPastRecipes = (recipeId, recipeTitle, recipeImage) => {
return {
type: ADD_TO_PAST_RECIPES,
recipeId,
recipeTitle,
recipeImage,
};
};
// THUNK CREATORS
export const getPastRecipesThunk = userId => {
return async function(dispatch) {
try {
let pastRecipesObj = {};
await db
.collection('users')
.doc(`${userId}`)
.collection('pastRecipes')
.get()
.then(snapshot => {
snapshot.forEach(doc => {
pastRecipesObj[`${doc.id}`] = doc.data();
});
});
dispatch(getPastRecipes(Object.values(pastRecipesObj)));
} catch (error) {
console.log('Error!', error);
}
};
};
export const addToPastRecipesThunk = (
userId,
recipeId,
recipeTitle,
recipeImage
) => {
return async function(dispatch) {
try {
let recipeObj = { id: recipeId, title: recipeTitle, image: recipeImage };
await db
.collection('users')
.doc(`${userId}`)
.collection('pastRecipes')
.doc(`${recipeId}`)
.set(recipeObj);
dispatch(addToPastRecipes(recipeId, recipeTitle, recipeImage));
} catch (error) {
console.log('Error!', error);
}
};
};
// Past Recipes Reducer
function pastRecipesReducer(state = { pastRecipes: [] }, action) {
switch (action.type) {
case GET_PAST_RECIPES_FROM_STORE:
return state;
case CLEAR_PAST_RECIPES_FROM_STORE:
return { ...state, pastRecipes: [] };
case GOT_PAST_RECIPES:
return { ...state, pastRecipes: action.pastRecipes };
case ADD_TO_PAST_RECIPES:
let recipeObj = {
id: action.recipeId,
title: action.recipeTitle,
image: action.recipeImage,
};
let recipeArr = state.pastRecipes.filter(
elemObj => elemObj.id === action.recipeId
);
// Add the recipe from action, only if it was absent in the state.
if (recipeArr.length === 0) {
return { ...state, pastRecipes: [...state.pastRecipes, recipeObj] };
}
// Do not add to the state, if recipe was already present.
else if (recipeArr.length === 1) {
return state;
}
default:
return state;
}
}
export default pastRecipesReducer;
<file_sep>import { createAppContainer } from 'react-navigation';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import { createStackNavigator } from 'react-navigation-stack';
import { Root } from 'native-base';
import React from 'react';
import { Provider } from 'react-redux';
import store from './src/store/index';
import SearchIngredientsScreen from './src/screens/SearchIngredientsScreen';
import SingleRecipeScreen from './src/screens/SingleRecipeScreen';
import BarcodeScannerScreen from './src/screens/BarcodeScannerScreen';
import InstructionScreen from './src/screens/InstructionsScreen';
import LoginScreen from './src/screens/LoginScreen';
import MyRecipesScreen from './src/screens/MyRecipesScreen';
import WelcomeScreen from './src/screens/WelcomeScreen';
const WelcomeStack = createStackNavigator(
{
Welcome: {
screen: WelcomeScreen,
title: 'Home',
},
Login: LoginScreen,
},
{
initialRouteName: 'Welcome',
}
);
const SearchRecipesStack = createStackNavigator(
{
Search: SearchIngredientsScreen,
SingleRecipe: SingleRecipeScreen,
BarcodeScanner: BarcodeScannerScreen,
Instruction: InstructionScreen,
Login: LoginScreen,
},
{
initialRouteName: 'Search',
defaultNavigationOptions: {
title: 'Search for Recipes',
},
}
);
const MyRecipesStack = createStackNavigator(
{
MyRecipes: MyRecipesScreen,
SingleRecipe: SingleRecipeScreen,
},
{
initialRouteName: 'MyRecipes',
defaultNavigationOptions: {
title: 'My Recipes',
},
}
);
let Navigation = createAppContainer(
createBottomTabNavigator(
{
Home: {
screen: WelcomeStack,
navigationOptions: {
tabBarVisible: false,
},
},
'Search Recipes': SearchRecipesStack,
'My Recipes': MyRecipesStack,
},
{
tabBarOptions: {
activeBackgroundColor: '#304b5a',
labelStyle: {
fontSize: 16,
fontWeight: 'bold',
color: '#F2C04C',
marginBottom: 15
},
style: {
backgroundColor: '#141414',
},
},
}
)
);
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<Root>
<Navigation />
</Root>
</Provider>
);
}
}
<file_sep>import React from 'react';
import { View, Text, FlatList } from 'react-native';
import InstructionList from '../components/InstructionList';
import styles from '../styles/InstructionsScreenStyle';
const InstructionScreen = ({ navigation }) => {
const additionalInfo = navigation.getParam('additionalInfo');
const prepTime = navigation.getParam('prepTime');
const servings = navigation.getParam('servings');
const convertPrepTime = (prepTime) => {
let readyTime = "";
if (prepTime <= 60 && prepTime > 0) {
readyTime = `${prepTime} Minutes`;
} else {
const hours = Math.floor(prepTime / 60);
const minutes = prepTime % 60;
readyTime = `${hours} Hours`;
if (minutes > 0){
readyTime += ` ${minutes} Minutes`;
}
}
return readyTime;
}
return (
<View style={styles.container}>
<Text style={styles.textTitle}>Recipe Instructions</Text>
{
prepTime !== 0 && servings !== 0 ?
(
<View style={styles.addtional}>
<Text style={styles.textAddtional}>Prep and Cook Time: { convertPrepTime(prepTime) }</Text>
<Text style={styles.textAddtional}>Servings: { servings }</Text>
</View>
) : null
}
<FlatList
data={additionalInfo}
keyExtractor={(item, index) => 'key2'+ index}
renderItem={({ item, index }) => {
return (
<InstructionList allInstructions={item} />
);
}
}
/>
</View>
)
}
export default InstructionScreen;<file_sep>const data = [
{
"id": 21198,
"title": "Guacamole",
"image": "https://spoonacular.com/recipeImages/21198-312x231.jpg",
"imageType": "jpg",
"usedIngredientCount": 2,
"missedIngredientCount": 0,
"missedIngredients": [],
"usedIngredients": [
{
"id": 9037,
"amount": 2.0,
"unit": "large",
"unitLong": "larges",
"unitShort": "large",
"aisle": "Produce",
"name": "avocados",
"original": "2 large ripe avocados, diced",
"originalString": "2 large ripe avocados, diced",
"originalName": "ripe avocados, diced",
"metaInformation": [
"diced",
"ripe"
],
"extendedName": "diced avocados",
"image": "https://spoonacular.com/cdn/ingredients_100x100/avocado.jpg"
},
{
"id": 11165,
"amount": 2.0,
"unit": "tbsp",
"unitLong": "tablespoons",
"unitShort": "Tbsp",
"aisle": "Produce;Spices and Seasonings",
"name": "cilantro",
"original": "2 tbsp cilantro, or more to taste",
"originalString": "2 tbsp cilantro, or more to taste",
"originalName": "cilantro, or more to taste",
"metaInformation": [
"to taste"
],
"image": "https://spoonacular.com/cdn/ingredients_100x100/cilantro.png"
}
],
"unusedIngredients": [
{
"id": 11282,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Produce",
"name": "onion",
"original": "onion",
"originalString": "onion",
"originalName": "onion",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/brown-onion.png"
},
{
"id": 5006,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Meat",
"name": "chicken",
"original": "chicken",
"originalString": "chicken",
"originalName": "chicken",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/whole-chicken.jpg"
}
],
"likes": 0
},
{
"id": 1009580,
"title": "How to Make Shredded Chicken in the Instant Pot",
"image": "https://spoonacular.com/recipeImages/1009580-312x231.png",
"imageType": "png",
"usedIngredientCount": 1,
"missedIngredientCount": 0,
"missedIngredients": [],
"usedIngredients": [
{
"id": 5006,
"amount": 1.0,
"unit": "lb",
"unitLong": "pound",
"unitShort": "lb",
"aisle": "Meat",
"name": "chicken",
"original": "1lb chicken",
"originalString": "1lb chicken",
"originalName": "chicken",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/whole-chicken.jpg"
}
],
"unusedIngredients": [
{
"id": 9037,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Produce",
"name": "avocado",
"original": "avocado",
"originalString": "avocado",
"originalName": "avocado",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/avocado.jpg"
},
{
"id": 11282,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Produce",
"name": "onion",
"original": "onion",
"originalString": "onion",
"originalName": "onion",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/brown-onion.png"
},
{
"id": 11165,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Produce;Spices and Seasonings",
"name": "cilantro",
"original": "cilantro",
"originalString": "cilantro",
"originalName": "cilantro",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/cilantro.png"
}
],
"likes": 1
},
{
"id": 1082510,
"title": "Crispy Fried Shallots",
"image": "https://spoonacular.com/recipeImages/1082510-312x231.jpg",
"imageType": "jpg",
"usedIngredientCount": 0,
"missedIngredientCount": 1,
"missedIngredients": [
{
"id": 11677,
"amount": 8.0,
"unit": "small",
"unitLong": "smalls",
"unitShort": "small",
"aisle": "Produce",
"name": "shallots",
"original": "8 small shallots, peeled",
"originalString": "8 small shallots, peeled",
"originalName": "shallots, peeled",
"metaInformation": [
"peeled"
],
"image": "https://spoonacular.com/cdn/ingredients_100x100/shallots.jpg"
}
],
"usedIngredients": [],
"unusedIngredients": [
{
"id": 9037,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Produce",
"name": "avocado",
"original": "avocado",
"originalString": "avocado",
"originalName": "avocado",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/avocado.jpg"
},
{
"id": 11282,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Produce",
"name": "onion",
"original": "onion",
"originalString": "onion",
"originalName": "onion",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/brown-onion.png"
},
{
"id": 11165,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Produce;Spices and Seasonings",
"name": "cilantro",
"original": "cilantro",
"originalString": "cilantro",
"originalName": "cilantro",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/cilantro.png"
},
{
"id": 5006,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Meat",
"name": "chicken",
"original": "chicken",
"originalString": "chicken",
"originalName": "chicken",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/whole-chicken.jpg"
}
],
"likes": 1
},
{
"id": 21202,
"title": "Guacamole",
"image": "https://spoonacular.com/recipeImages/21202-312x231.jpg",
"imageType": "jpg",
"usedIngredientCount": 2,
"missedIngredientCount": 2,
"missedIngredients": [
{
"id": 9160,
"amount": 1.0,
"unit": "",
"unitLong": "",
"unitShort": "",
"aisle": "Produce",
"name": "juice of lime",
"original": "1 lime, juiced",
"originalString": "1 lime, juiced",
"originalName": "lime, juiced",
"metaInformation": [
"juiced"
],
"extendedName": "lime (juice)",
"image": "https://spoonacular.com/cdn/ingredients_100x100/lime-juice.png"
},
{
"id": 10011282,
"amount": 0.3333333333333333,
"unit": "cup",
"unitLong": "cups",
"unitShort": "cup",
"aisle": "Produce",
"name": "red onion",
"original": "1/3 cup red onion, minced",
"originalString": "1/3 cup red onion, minced",
"originalName": "red onion, minced",
"metaInformation": [
"red",
"minced"
],
"image": "https://spoonacular.com/cdn/ingredients_100x100/red-onion.png"
}
],
"usedIngredients": [
{
"id": 11165,
"amount": 1.0,
"unit": "tbsp",
"unitLong": "tablespoon",
"unitShort": "Tbsp",
"aisle": "Produce;Spices and Seasonings",
"name": "cilantro",
"original": "1 tbsp chopped cilantro",
"originalString": "1 tbsp chopped cilantro",
"originalName": "chopped cilantro",
"metaInformation": [
"chopped"
],
"image": "https://spoonacular.com/cdn/ingredients_100x100/cilantro.png"
},
{
"id": 9037,
"amount": 3.0,
"unit": "medium",
"unitLong": "mediums",
"unitShort": "medium",
"aisle": "Produce",
"name": "hass avocados",
"original": "3 medium hass avocados, halved",
"originalString": "3 medium hass avocados, halved",
"originalName": "hass avocados, halved",
"metaInformation": [
"halved"
],
"image": "https://spoonacular.com/cdn/ingredients_100x100/avocado.jpg"
}
],
"unusedIngredients": [
{
"id": 11282,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Produce",
"name": "onion",
"original": "onion",
"originalString": "onion",
"originalName": "onion",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/brown-onion.png"
},
{
"id": 5006,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Meat",
"name": "chicken",
"original": "chicken",
"originalString": "chicken",
"originalName": "chicken",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/whole-chicken.jpg"
}
],
"likes": 39
},
{
"id": 249202,
"title": "Guacamole",
"image": "https://spoonacular.com/recipeImages/21202-312x231.jpg",
"imageType": "jpg",
"usedIngredientCount": 2,
"missedIngredientCount": 2,
"missedIngredients": [
{
"id": 9160,
"amount": 1.0,
"unit": "",
"unitLong": "",
"unitShort": "",
"aisle": "Produce",
"name": "juice of lime",
"original": "1 lime, juiced",
"originalString": "1 lime, juiced",
"originalName": "lime, juiced",
"metaInformation": [
"juiced"
],
"extendedName": "lime (juice)",
"image": "https://spoonacular.com/cdn/ingredients_100x100/lime-juice.png"
},
{
"id": 10011282,
"amount": 0.3333333333333333,
"unit": "cup",
"unitLong": "cups",
"unitShort": "cup",
"aisle": "Produce",
"name": "red onion",
"original": "1/3 cup red onion, minced",
"originalString": "1/3 cup red onion, minced",
"originalName": "red onion, minced",
"metaInformation": [
"red",
"minced"
],
"image": "https://spoonacular.com/cdn/ingredients_100x100/red-onion.png"
}
],
"usedIngredients": [
{
"id": 11165,
"amount": 1.0,
"unit": "tbsp",
"unitLong": "tablespoon",
"unitShort": "Tbsp",
"aisle": "Produce;Spices and Seasonings",
"name": "cilantro",
"original": "1 tbsp chopped cilantro",
"originalString": "1 tbsp chopped cilantro",
"originalName": "chopped cilantro",
"metaInformation": [
"chopped"
],
"image": "https://spoonacular.com/cdn/ingredients_100x100/cilantro.png"
},
{
"id": 9037,
"amount": 3.0,
"unit": "medium",
"unitLong": "mediums",
"unitShort": "medium",
"aisle": "Produce",
"name": "hass avocados",
"original": "3 medium hass avocados, halved",
"originalString": "3 medium hass avocados, halved",
"originalName": "hass avocados, halved",
"metaInformation": [
"halved"
],
"image": "https://spoonacular.com/cdn/ingredients_100x100/avocado.jpg"
}
],
"unusedIngredients": [
{
"id": 11282,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Produce",
"name": "onion",
"original": "onion",
"originalString": "onion",
"originalName": "onion",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/brown-onion.png"
},
{
"id": 5006,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Meat",
"name": "chicken",
"original": "chicken",
"originalString": "chicken",
"originalName": "chicken",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/whole-chicken.jpg"
}
],
"likes": 39
},
{
"id": 22202,
"title": "Guacamole",
"image": "https://spoonacular.com/recipeImages/21202-312x231.jpg",
"imageType": "jpg",
"usedIngredientCount": 2,
"missedIngredientCount": 2,
"missedIngredients": [
{
"id": 9160,
"amount": 1.0,
"unit": "",
"unitLong": "",
"unitShort": "",
"aisle": "Produce",
"name": "juice of lime",
"original": "1 lime, juiced",
"originalString": "1 lime, juiced",
"originalName": "lime, juiced",
"metaInformation": [
"juiced"
],
"extendedName": "lime (juice)",
"image": "https://spoonacular.com/cdn/ingredients_100x100/lime-juice.png"
},
{
"id": 10011282,
"amount": 0.3333333333333333,
"unit": "cup",
"unitLong": "cups",
"unitShort": "cup",
"aisle": "Produce",
"name": "red onion",
"original": "1/3 cup red onion, minced",
"originalString": "1/3 cup red onion, minced",
"originalName": "red onion, minced",
"metaInformation": [
"red",
"minced"
],
"image": "https://spoonacular.com/cdn/ingredients_100x100/red-onion.png"
}
],
"usedIngredients": [
{
"id": 11165,
"amount": 1.0,
"unit": "tbsp",
"unitLong": "tablespoon",
"unitShort": "Tbsp",
"aisle": "Produce;Spices and Seasonings",
"name": "cilantro",
"original": "1 tbsp chopped cilantro",
"originalString": "1 tbsp chopped cilantro",
"originalName": "chopped cilantro",
"metaInformation": [
"chopped"
],
"image": "https://spoonacular.com/cdn/ingredients_100x100/cilantro.png"
},
{
"id": 9037,
"amount": 3.0,
"unit": "medium",
"unitLong": "mediums",
"unitShort": "medium",
"aisle": "Produce",
"name": "hass avocados",
"original": "3 medium hass avocados, halved",
"originalString": "3 medium hass avocados, halved",
"originalName": "hass avocados, halved",
"metaInformation": [
"halved"
],
"image": "https://spoonacular.com/cdn/ingredients_100x100/avocado.jpg"
}
],
"unusedIngredients": [
{
"id": 11282,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Produce",
"name": "onion",
"original": "onion",
"originalString": "onion",
"originalName": "onion",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/brown-onion.png"
},
{
"id": 5006,
"amount": 1.0,
"unit": "serving",
"unitLong": "serving",
"unitShort": "serving",
"aisle": "Meat",
"name": "chicken",
"original": "chicken",
"originalString": "chicken",
"originalName": "chicken",
"metaInformation": [],
"image": "https://spoonacular.com/cdn/ingredients_100x100/whole-chicken.jpg"
}
],
"likes": 39
}
]
<file_sep>import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
//by default an image wants to collapse itself
container: {
marginLeft: 15
},
recipeName: {
fontWeight: "bold",
fontSize: 16,
textAlign: 'center'
},
imageStyle: {
height: 120,
width: 250,
borderRadius: 5,
marginLeft: 45
}
});
export default styles;
<file_sep>import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
marginLeft: 5,
marginRight: 5,
maxHeight: 550
},
text: {
fontSize: 16,
margin: 5
},
label: {
fontSize: 18,
fontWeight: 'bold',
textDecorationLine: 'underline'
}
});
export default styles;<file_sep>import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
},
welcomeHeader: {
height: 90,
marginLeft: 20,
marginRight: 20,
marginTop: 60,
marginBottom: 20,
alignItems: 'center',
borderRadius: 5,
},
welcomeHeaderText: {
fontSize: 50,
fontWeight: 'bold',
color: '#F2C04C',
},
slogan: {
paddingTop: 15,
paddingBottom: 15,
fontSize: 16,
textAlignVertical: 'center',
textAlign: 'center',
fontStyle: 'italic',
color: '#F2C04C',
},
imageStyle: {
height: '100%',
width: '100%',
},
button: {
marginTop: 10,
width: 175,
color: '#F7E9D0',
marginBottom: 10,
alignItems: 'center',
justifyContent: 'center',
},
welcomeMessage: {
paddingTop: 15,
color: '#F7E9D0',
fontSize: 25,
textAlignVertical: 'center',
textAlign: 'center',
},
searchButton: {
marginTop: 20,
width: 330,
color: '#F7E9D0',
marginBottom: 10,
alignItems: 'center',
justifyContent: 'center',
},
logOutButton: {
marginLeft: 80,
marginTop: 5,
width: 150,
color: '#F7E9D0',
marginBottom: 10,
alignItems: 'center',
justifyContent: 'center',
},
buttonText: {
fontSize: 18,
color: '#F2C04C',
fontWeight: '600'
},
searchButtonText: {
fontSize: 18,
color: '#dfa110',
fontWeight: 'bold',
},
logoutButtonText: {
fontSize: 18,
color: '#dfa110',
},
});
export default styles;<file_sep>import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
height: 40,
flex: 1,
alignItems: 'center',
marginLeft: 20,
marginRight: 20,
marginTop: 30,
marginBottom: 400,
},
imageStyle: {
height: '100%',
width: '100%',
},
loginHeader: {
paddingTop: 70,
fontWeight: 'bold',
color: '#F2C04C',
fontSize: 18,
textAlignVertical: "center",
textAlign: "center",
},
textInput: {
backgroundColor: 'white',
height: 40,
width: '90%',
borderColor: 'gray',
borderWidth: 1,
marginTop: 8,
fontWeight: 'bold'
},
button: {
width: 125,
color: '#F7E9D0',
marginTop: 15,
marginLeft: 10,
marginBottom: 5,
alignItems: 'center',
justifyContent: 'center',
},
buttonText: {
fontSize: 18,
fontWeight: 'bold',
color: '#F2C04C'
},
});
export default styles;<file_sep>import React from 'react';
import {
View,
Text,
Image,
} from 'react-native';
import { Toast, Button } from 'native-base';
import { SPOON_API } from 'react-native-dotenv';
import spoonacular from '../api/spoonacular';
import { connect } from 'react-redux';
import styles from '../styles/SingleRecipeStyle';
import FullIngredientsList from '../components/FullIngredientsList';
import UsedIngredientsFromList from '../components/UsedIngredientsFromList'
import { getCurrentUser } from '../store/usersReducer';
import { addToPastRecipesThunk } from '../store/pastRecipesReducer';
import {
getWishListFromStore,
getWishListThunk,
addToWishListThunk,
removeFromWishListThunk,
} from '../store/wishListReducer';
class SingleRecipeScreen extends React.Component {
isMounted = false;
constructor(props) {
super(props);
this.state = {
additionalInfo: [],
extendedIngredients: [],
prepTime: 0,
servings: 0
}
this.searchInstructionAndAddiInfoData = this.searchInstructionAndAddiInfoData.bind(
this
);
this.addToWishList = this.addToWishList.bind(this);
this.removeFromWishList = this.removeFromWishList.bind(this);
this.displayLogicHandler = this.displayLogicHandler.bind(this);
this.addToPastRecipes = this.addToPastRecipes.bind(this);
}
searchInstructionAndAddiInfoData = async (recipeId) => {
let url = `/${recipeId}/information?apiKey=${SPOON_API}`;
try {
const additionalInfoData = await spoonacular.get(url);
if(additionalInfoData) {
if(additionalInfoData.data["analyzedInstructions"].length >= 1 && additionalInfoData.data["extendedIngredients"].length >= 1) {
this.setState({
prepTime: additionalInfoData.data["readyInMinutes"],
servings: additionalInfoData.data["servings"],
additionalInfo: additionalInfoData.data["analyzedInstructions"],
extendedIngredients: additionalInfoData.data["extendedIngredients"]
})
} else if(additionalInfoData.data["analyzedInstructions"].length >= 1 && additionalInfoData.data["extendedIngredients"].length < 1) {
this.setState({
prepTime: additionalInfoData.data["readyInMinutes"],
servings: additionalInfoData.data["servings"],
additionalInfo: additionalInfoData.data["analyzedInstructions"],
})
} else if(additionalInfoData.data["analyzedInstructions"].length < 1 && additionalInfoData.data["extendedIngredients"].length >= 1) {
this.setState({
extendedIngredients: additionalInfoData.data["extendedIngredients"]
})
}
}
} catch (error) {
console.log('Error', error)
}
};
addToPastRecipes(userId, isLoggedIn) {
const recipe = this.props.navigation.getParam('recipe');
if (isLoggedIn === true) {
this.props.addToPastRecipesThunk(
userId,
recipe.id,
recipe.title,
recipe.image
);
}
this.props.navigation.navigate('Instruction', {
additionalInfo: this.state.additionalInfo,
prepTime: this.state.prepTime,
servings: this.state.servings
});
}
addToWishList = async (
userId,
recipeId,
title,
image,
isRecipeInWishList
) => {
try {
if (isRecipeInWishList === true) {
// already exists
Toast.show({
text: `${title} already exists in your Wish List!`,
buttonText: 'Okay',
duration: 3000,
type: 'warning',
});
} else {
// add to the wishlist
this.props.addToWishListThunk(userId, recipeId, title, image);
Toast.show({
text: `${title} has been added successfully to your Wish List!`,
buttonText: 'Okay',
duration: 3000,
type: 'success',
});
}
} catch (error) {
console.log('Error! ', error);
}
};
removeFromWishList = (userId, recipeId, title) => {
this.props.removeFromWishListThunk(userId, recipeId);
Toast.show({
text: `${title} has been removed successfully from your Wish List.`,
buttonText: 'Okay',
duration: 3000,
type: 'danger',
});
};
// Function to check if current user is logged in
// and if the given recipe is in user's wish list
displayLogicHandler(recipeId) {
this.props.getCurrentUser();
this.props.getWishListFromStore();
let isLoggedIn = false;
let isRecipeInWishList = false;
const { currentUser, wishList } = this.props;
if (currentUser !== undefined && currentUser.id) {
isLoggedIn = true;
//If wish list is empty,
if (JSON.stringify(wishList) === JSON.stringify([])) {
// try to retrieve it from database
this.props.getWishListThunk(currentUser.id);
}
let recipeArr = this.props.wishList.filter(
elemObj => elemObj.id === recipeId
);
if (recipeArr.length === 1) {
isRecipeInWishList = true;
}
}
return { isLoggedIn, isRecipeInWishList };
}
doUsedIngredientsExist(recipe) {
if(recipe.usedIngredientCount && recipe.usedIngredientCount > 0) {
return true;
} else {
return false;
}
}
formatIngredientName = ingredient => {
let formatted = ingredient[0].toUpperCase() + ingredient.slice(1);
return formatted;
};
componentDidMount() {
this.isMounted = true;
const recipe = this.props.navigation.getParam('recipe');
this.searchInstructionAndAddiInfoData(recipe.id);
}
componentWillUnmount() {
this.isMounted = false;
}
render() {
const { currentUser } = this.props;
const recipe = this.props.navigation.getParam('recipe');
let displayFlags = this.displayLogicHandler(recipe.id);
return (
<View style={styles.container}>
<Text style={styles.recipeNameTitle}>
{this.formatIngredientName(recipe.title)}
</Text>
<Image style={styles.imageStyle} source={{ uri: recipe.image }} />
{
this.doUsedIngredientsExist(recipe) === true ?
(
<UsedIngredientsFromList recipe={recipe}/>
) : null
}
<Text style={styles.recipeName}>Full Ingredient List:</Text>
<FullIngredientsList extendedIngredients={this.state.extendedIngredients}/>
{displayFlags.isLoggedIn === false ? null : (
<View>
{displayFlags.isRecipeInWishList === false ? (
<Button
rounded
success
style={styles.button}
onPress={() =>
this.addToWishList(
currentUser.id,
recipe.id,
recipe.title,
recipe.image,
displayFlags.isRecipeInWishList
)
}
>
<Text style={styles.buttonText}>Add to Wish List</Text>
</Button>
) : (
<Button
rounded
danger
style={styles.button}
onPress={() =>
this.removeFromWishList(
currentUser.id,
recipe.id,
recipe.title
)
}
>
<Text style={styles.buttonText}>Remove from Wish List</Text>
</Button>
)}
</View>
)}
{
this.state.additionalInfo.length > 0 ?
(
<Button
rounded
dark
style={styles.button}
onPress={() =>
this.addToPastRecipes(
currentUser.id,
displayFlags.isLoggedIn
)
}
>
<Text style={styles.buttonText}>Recipe Instructions</Text>
</Button>
) : null
}
</View>
);
}
}
const mapStateToProps = state => {
return {
currentUser: state.usersReducer.currentUser,
pastRecipes: state.pastRecipesReducer.pastRecipes,
wishList: state.wishListReducer.wishList,
};
};
const mapDispatchToProps = dispatch => {
return {
getCurrentUser: () => dispatch(getCurrentUser()),
addToPastRecipesThunk: (userId, recipeId, recipeTitle, recipeImage) =>
dispatch(
addToPastRecipesThunk(userId, recipeId, recipeTitle, recipeImage)
),
getWishListThunk: userId => dispatch(getWishListThunk(userId)),
getWishListFromStore: () => dispatch(getWishListFromStore()),
addToWishListThunk: (userId, recipeId, recipeTitle, recipeImage) =>
dispatch(addToWishListThunk(userId, recipeId, recipeTitle, recipeImage)),
removeFromWishListThunk: (userId, recipeId) =>
dispatch(removeFromWishListThunk(userId, recipeId)),
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(SingleRecipeScreen);
<file_sep>import axios from 'axios';
import { BUYCOTT_API } from 'react-native-dotenv';
export default axios.create({
baseURL: 'https://buycott.com/api/v4/products/lookup',
headers: {
Authorization: `Bearer ${BUYCOTT_API}`
}
})<file_sep>import db from '../api/db/database';
// ACTION TYPES
export const GET_WISHLIST_FROM_STORE = 'GET_WISHLIST_FROM_STORE';
export const CLEAR_WISHLIST_FROM_STORE = 'CLEAR_WISHLIST_FROM_STORE';
export const GOT_WISHLIST = 'GOT_WISHLIST';
export const ADD_TO_WISHLIST = 'ADD_TO_WISHLIST';
export const REMOVE_FROM_WISHLIST = 'REMOVE_FROM_WISHLIST';
// ACTION CREATORS
export const getWishListFromStore = () => {
return {
type: GET_WISHLIST_FROM_STORE,
};
};
export const clearWishListFromStore = () => {
return {
type: CLEAR_WISHLIST_FROM_STORE,
};
};
export const gotWishList = wishList => {
return {
type: GOT_WISHLIST,
wishList,
};
};
export const addToWishList = (recipeId, recipeTitle, recipeImage) => {
return {
type: ADD_TO_WISHLIST,
recipeId,
recipeTitle,
recipeImage,
};
};
export const removeFromWishList = recipeId => {
return {
type: REMOVE_FROM_WISHLIST,
recipeId,
};
};
// THUNK CREATORS
export const getWishListThunk = userId => {
return async function(dispatch) {
try {
let wishListObj = {};
await db
.collection('users')
.doc(`${userId}`)
.collection('wishList')
.get()
.then(snapshot => {
snapshot.forEach(doc => {
wishListObj[`${doc.id}`] = doc.data();
});
});
dispatch(gotWishList(Object.values(wishListObj)));
} catch (error) {
console.log('Error!', error);
}
};
};
export const addToWishListThunk = (
userId,
recipeId,
recipeTitle,
recipeImage
) => {
return async function(dispatch) {
try {
let recipeObj = { id: recipeId, title: recipeTitle, image: recipeImage };
await db
.collection('users')
.doc(`${userId}`)
.collection('wishList')
.doc(`${recipeId}`)
.set(recipeObj);
dispatch(addToWishList(recipeId, recipeTitle, recipeImage));
} catch (error) {
console.log('Error!', error);
}
};
};
export const removeFromWishListThunk = (userId, recipeId) => {
return async function(dispatch) {
await db
.collection('users')
.doc(`${userId}`)
.collection('wishList')
.doc(`${recipeId}`)
.delete()
.then(function() {})
.catch(function(error) {
console.error('Error removing document: ', error);
});
dispatch(removeFromWishList(recipeId));
};
};
// Wish List Reducer
function wishListReducer(state = { wishList: [] }, action) {
switch (action.type) {
case GET_WISHLIST_FROM_STORE:
return state;
case CLEAR_WISHLIST_FROM_STORE:
return { ...state, wishList: [] };
case GOT_WISHLIST:
return { ...state, wishList: action.wishList };
case ADD_TO_WISHLIST:
let recipeObj = {
id: action.recipeId,
title: action.recipeTitle,
image: action.recipeImage,
};
let recipeArr = state.wishList.filter(
elemObj => elemObj.id === action.recipeId
);
// Add the recipe from action, only if it was absent in the state.
if (recipeArr.length === 0) {
return { ...state, wishList: [...state.wishList, recipeObj] };
}
// Do not add to the state, if recipe was already present.
else if (recipeArr.length === 1) {
return state;
}
case REMOVE_FROM_WISHLIST:
return {
...state,
wishList: [...state.wishList].filter(
elemObj => elemObj.id !== action.recipeId
),
};
default:
return state;
}
}
export default wishListReducer;
<file_sep>import React from 'react';
import {
View,
Text,
Image,
} from 'react-native';
import styles from '../styles/RecipeDetailStyle'
const RecipeDetail = ({ recipe }) => {
return (
<View style={styles.container}>
<Text style={styles.recipeName}>{recipe.title}</Text>
<Image style={styles.imageStyle} source={{ uri: recipe.image }} />
</View>
)
}
export default RecipeDetail;<file_sep>import * as firebase from 'firebase';
import { FIREBASE_API } from 'react-native-dotenv';
import 'firebase/firestore';
const config = {
apiKey: `${FIREBASE_API}`,
authDomain: 'ingredia-dc183.firebaseapp.com',
databaseURL: 'https://ingredia-dc183.firebaseapp.com',
projectId: 'ingredia-dc183',
storageBucket: 'ingredia-dc183.appspot.com',
messagingSenderId: '1083112709962',
};
const app = firebase.initializeApp(config);
const db = firebase.firestore(app);
export default db;
<file_sep>import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import * as Permissions from 'expo-permissions';
import { BUYCOTT_API } from 'react-native-dotenv';
import buycott from '../api/buycott';
import { BarCodeScanner } from 'expo-barcode-scanner';
import { withNavigation } from 'react-navigation';
const BarcodeScannerScreen = ({ navigation }) => {
const [hasCameraPermission, setCameraPermission] = useState(null);
const [scanned, setScanned] = useState(false);
const getPermissionsAsync = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
if (status === 'granted') {
setCameraPermission(true);
}
};
// Search Buycott API to retrieve the product name, for which the user has scanned the barcode.
const searchBarcodeApi = async barcode => {
try {
const { data } = await buycott.get('/', {
params: {
barcode: barcode,
access_token: BUYCOTT_API,
},
});
let productName;
// If we have a product name,
if (data.products[0].product_name) {
// Extract the product name.
productName = data.products[0].product_name;
// Navigate back to Search screen with the found product name.
const getHandler = navigation.getParam('handleBarcode');
getHandler(productName);
navigation.navigate('Search', { ingredientName: productName });
navigation.setParams({ ingredientName: null });
}
} catch (error) {
console.log('Error!, ', error);
}
};
const handleBarCodeScanned = async ({ type, data }) => {
setScanned(true);
searchBarcodeApi(data);
};
useEffect(() => {
getPermissionsAsync();
});
if (hasCameraPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View
style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-end',
}}
>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
/>
{scanned && (
<Button title={'Tap to Scan Again'} onPress={() => setScanned(false)} />
)}
</View>
);
};
export default withNavigation(BarcodeScannerScreen);
<file_sep>// ACTION TYPES
export const GET_CURRENT_USER = 'GET_CURRENT_USER';
export const UPDATE_CURRENT_USER = 'UPDATE_CURRENT_USER';
// ACTION CREATORS
export const getCurrentUser = () => {
return {
type: GET_CURRENT_USER,
};
};
export const updateCurrentUser = (userId, userEmail, status) => {
return {
type: UPDATE_CURRENT_USER,
userId,
userEmail,
status,
};
};
// THUNK CREATORS
// Users Reducer
function usersReducer(state = { currentUser: {} }, action) {
switch (action.type) {
case GET_CURRENT_USER:
return state;
case UPDATE_CURRENT_USER:
if (action.status === 'loggedIn') {
let userObj = { id: action.userId, email: action.userEmail };
return { ...state, currentUser: userObj };
} else if (action.status === 'loggedOut')
return { ...state, currentUser: {} };
default:
return state;
}
}
export default usersReducer;
<file_sep>import React from 'react';
import { Text, View } from 'react-native';
import { ScrollView } from 'react-native-gesture-handler';
import { Button, Tabs, Tab } from 'native-base';
import { connect } from 'react-redux';
import styles from '../styles/MyRecipeScreenStyle';
import { getCurrentUser } from '../store/usersReducer';
import {
getPastRecipesFromStore,
getPastRecipesThunk,
} from '../store/pastRecipesReducer';
import {
getWishListFromStore,
getWishListThunk,
} from '../store/wishListReducer';
import UserPastRecipesList from '../components/UserPastRecipesList';
import UserWishList from '../components/UserWishList';
class MyRecipesScreen extends React.PureComponent {
constructor(props) {
super(props);
this.displayLogicHandler = this.displayLogicHandler.bind(this);
}
displayLogicHandler() {
let isLoggedIn;
let isLoading;
let doMyRecipesExist;
let doPastRecipesExists;
let doWishListExists;
// Retrieve current user, past recipes and wish list from Redux store
this.props.getCurrentUser();
this.props.getPastRecipesFromStore();
this.props.getWishListFromStore();
const { currentUser, pastRecipes, wishList } = this.props;
// Check if current user is logged in,
if (currentUser !== undefined && currentUser.id) {
isLoggedIn = true;
//If both, pastRecipes and wishlist, are empty,
if (
JSON.stringify(pastRecipes) === JSON.stringify([]) &&
JSON.stringify(wishList) === JSON.stringify([])
) {
// That means the data is still loading
isLoading === true;
// And because they are empty, try to retrieve both lists,
// past recipes and wishlist, from the databse
this.props.getPastRecipesThunk(currentUser.id);
this.props.getWishListThunk(currentUser.id);
}
// Else if both lists are not empty, then data is loaded.
else {
isLoading = false;
}
// For past recipes, check if data has more than just 'recipe0' doc
if (pastRecipes.length > 1) {
doPastRecipesExists = true;
} else {
doPastRecipesExists = false;
}
// For wish list, check if data has more than just 'recipe0' doc
if (wishList.length > 1) {
doWishListExists = true;
} else {
doWishListExists = false;
}
// My Recipes exist, if at least one of the two lists exists
if (doPastRecipesExists === true || doWishListExists === true) {
doMyRecipesExist = true;
} else {
doMyRecipesExist = false;
}
}
// Else, current user is not logged in
else {
isLoggedIn = false;
}
return {
isLoggedIn,
isLoading,
doMyRecipesExist,
doPastRecipesExists,
doWishListExists,
};
}
render() {
const { pastRecipes, wishList } = this.props;
const displayFlags = this.displayLogicHandler();
return (
<View style={styles.container}>
{displayFlags.isLoggedIn === false ? (
<View>
<Text style={styles.messageLine1}>To Access the My Recipes Feature:</Text>
<Text style={styles.messageLine2}>Please Login or Sign-Up!</Text>
<Button
rounded dark
style={styles.loginButton}
onPress={() => this.props.navigation.navigate('Login')}
>
<Text style={styles.loginButtonText}>Login or Sign-Up</Text>
</Button>
</View>
) : displayFlags.isLoading === true ? (
<View>
<Text style={styles.messageLine2}>Loading...</Text>
</View>
) : displayFlags.doMyRecipesExist === false ? (
<View>
<Text style={styles.messageLine1}>No Recipes to Show!</Text>
<Text style={styles.messageLine2}>Please Add Recipes</Text>
</View>
) : displayFlags.doPastRecipesExists === true &&
displayFlags.doWishListExists === true ? (
<View>
<Tabs>
<Tab heading='Your Past Recipes'>
<ScrollView style={{ minHeight: 100 }}>
<UserPastRecipesList allRecipes={pastRecipes} />
</ScrollView>
</Tab>
<Tab heading='Your Wish List'>
<ScrollView style={{ minHeight: 100 }}>
<UserWishList allRecipes={wishList} />
</ScrollView>
</Tab>
</Tabs>
</View>
) : displayFlags.doPastRecipesExists === true ? (
<View>
<Tabs>
<Tab heading='Your Past Recipes'>
<ScrollView style={{ minHeight: 100 }}>
<UserPastRecipesList allRecipes={pastRecipes} />
</ScrollView>
</Tab>
<Tab heading='Your Wish List'>
<Text style={styles.messageLine1}>Currently There are No Recipes in your Wish List!</Text>
</Tab>
</Tabs>
</View>
) : displayFlags.doWishListExists === true ? (
<View>
<Tabs>
<Tab heading='Your Past Recipes'>
<Text style={styles.messageLine1}>Currently There are No Recipes in your Past Recipes!</Text>
</Tab>
<Tab heading='Your Wish List'>
<ScrollView style={{ minHeight: 100 }}>
<UserWishList allRecipes={wishList} />
</ScrollView>
</Tab>
</Tabs>
</View>
) : null}
</View>
);
}
}
const mapStateToProps = state => {
return {
currentUser: state.usersReducer.currentUser,
pastRecipes: state.pastRecipesReducer.pastRecipes,
wishList: state.wishListReducer.wishList,
};
};
const mapDispatchToProps = dispatch => {
return {
getCurrentUser: () => dispatch(getCurrentUser()),
getPastRecipesFromStore: () => dispatch(getPastRecipesFromStore()),
getPastRecipesThunk: userId => dispatch(getPastRecipesThunk(userId)),
getWishListFromStore: () => dispatch(getWishListFromStore()),
getWishListThunk: userId => dispatch(getWishListThunk(userId)),
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(MyRecipesScreen);
<file_sep>import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { combineReducers } from 'redux';
import usersReducer from './usersReducer';
import pastRecipesReducer from './pastRecipesReducer';
import wishListReducer from './wishListReducer';
const rootReducer = combineReducers({
usersReducer,
pastRecipesReducer,
wishListReducer,
});
export default createStore(rootReducer, applyMiddleware(thunkMiddleware));
<file_sep>import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center',
flex: 1,
},
messageLine1: {
marginTop: 15,
fontSize: 22,
fontWeight: 'bold',
textAlignVertical: 'center',
textAlign: 'center',
textDecorationLine: 'underline'
},
messageLine2: {
marginTop: 15,
marginBottom: 15,
fontSize: 20,
textAlignVertical: 'center',
textAlign: 'center',
fontWeight: 'bold',
},
loginButton: {
height: 40,
borderRadius: 5,
marginHorizontal: 50,
marginTop: 10,
flexDirection: 'row',
marginBottom: 5,
alignItems: 'center',
justifyContent: 'center',
},
loginButtonText: {
fontSize: 18,
color: '#F2C04C',
fontWeight: 'bold',
},
listTitle: {
marginTop: 15,
marginBottom: 15,
fontSize: 18,
fontWeight: 'bold',
color: '#52809a',
},
});
export default styles;<file_sep>import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
header: {
fontSize: 18,
marginLeft: 15,
fontWeight: 'bold',
},
displayList: {
marginTop: 5,
marginLeft: 15,
minHeight: 50,
},
displayItem: {
fontSize: 18,
},
ingredientItemContainer: {
display: 'flex',
flexDirection: 'row',
},
removeIngredientButton: {
backgroundColor: '#e0e0e0',
marginHorizontal: 10,
justifyContent: 'center',
},
removeIngredientButtonText: {
color: 'black',
},
searchRecipeButton: {
height: 40,
borderRadius: 5,
marginHorizontal: 35,
marginTop: 10,
flexDirection: 'row',
marginBottom: 10,
marginLeft: 15,
width: 150,
alignItems: 'center',
justifyContent: 'center',
},
clearSearchResultsButton: {
marginTop: 10,
borderRadius: 5,
flexDirection: 'row',
marginBottom: 10,
height: 40,
width: 150,
justifyContent: 'center',
alignItems: 'center',
},
clearSearchResultsButtonText: {
fontSize: 16,
fontWeight: 'bold',
color: '#F2C04C',
textAlign: 'center',
},
addButton: {
marginTop: 15,
width: 60,
color: '#F7E9D0',
marginBottom: 10,
alignItems: 'center',
justifyContent: 'center',
},
barcodeButton: {
width: 200,
marginBottom: 5,
marginLeft: 15,
alignItems: 'center',
justifyContent: 'center',
},
searchButtonText: {
color: '#F2C04C',
fontSize: 16,
fontWeight: 'bold'
},
barcodeText: {
fontSize: 14,
fontWeight: 'bold',
color: '#F2C04C',
}
});
export default styles;<file_sep>import React from "react";
import Login from '../screens/LoginScreen';
describe('<Login />', () => {
it('renders', () => {
const wrapper = shallow(<Login />);
expect(wrapper.exists()).toBe(true);
});
});<file_sep># ingredia
#### Created by: <NAME>, <NAME> and <NAME>
## Overview
Inspired by our love for food and to spend money accordingly, we developed ingredia! It is a mobile application that we created with the intent of utilizing ingredients in your household that may otherwise go to waste. You know the ingredients you have sitting in your pantry or refrigerator that are probably going bad? Ingredia can help you with that! With its help, you can prepare some tasty recipes, and avoid feeling the guilt of throwing food away!
<img src="assets/ingrediaOpeningScreen.jpeg" width="25%" height="50%">
## User Experience
#### Guests :
Guests can easily search for recipes they can prepare with the ingredients that are available to them. They can either type in the ingredient or scan its barcode. The app will then render a list of recipes the user can whip up. If they select a recipe, they can view more information about that specific recipe, such as the preparation time, number of servings and the detailed steps.
#### Signed-up Users :
The users that have signed-up to use ingredia can log-in to their accounts. These users have access to all the features that guests have, in addition to the “My Recipes” tab. The "My Recipes" feature stores the user's “Past Recipes”, which contain the history of recipes made by that user, along with their “Wish List”. The "Wish List" is a collection of recipes saved by the user for future reference, or a recipe to prepare another time.
#### Highlighted Features :
Type/Scan Ingredients to Find Tasty Recipes | "My Recipes" Feature for Logged-In Users
:-------------------------:|:-------------------------:
<img src="assets/searchIngredientsGiphy.gif"> | <img src="assets/ingrediaMyRecipes.gif">
## Architecture
ingredia was built using JavaScript in Node.js environment. The front-end was designed using React Native and Expo CLI. In addition, NativeBase components were applied for styling. Redux was used to maintain the state of the application, specifically for a logged in user. It held that user’s information, along with Past Recipes and Wish List data associated with that user.
Instead of using a traditional RDBMS, we opted to use a NoSQL database. Cloud Firestore from Google Firebase was incorporated to maintain persistent data storage of user information, and the recipe data associated with each user.
We retrieved data from external APIs for the recipes, and ingredient information associated with a scanned barcode.
<img src="assets/ingrediaTechStack.png" width="60%" height="60%">
<file_sep>import React from 'react';
import {View, ScrollView, Text, FlatList } from 'react-native';
import styles from '../styles/InstructionListStyle';
const InstructionList = ({allInstructions}) => {
return (
<ScrollView style={styles.container}>
<FlatList
data={allInstructions["steps"]}
keyExtractor={(item, index) => 'key3'+index}
renderItem={({ item, index }) => {
return (
<View>
<Text style={styles.label}>{`Step ${index+1}: `}</Text>
<Text style={styles.text}>{item.step}</Text>
</View>
);
}}
/>
</ScrollView>
)
}
export default InstructionList;
<file_sep>import axios from 'axios';
import { SPOON_API } from 'react-native-dotenv';
export default axios.create({
baseURL: 'https://api.spoonacular.com/recipes',
headers: {
Authorization: `Bearer ${SPOON_API}`
}
})
|
ffe4a422af64a42a2b20bcaa2215b29aa12b39b1
|
[
"JavaScript",
"Markdown"
] | 25
|
JavaScript
|
Capstone-Project-Team-Dragons/ingredia
|
afa8b2552ce5187c0e56aef99f0c57f28524f2fa
|
10003e34c908770022606a3e863f52c135f142c9
|
refs/heads/master
|
<repo_name>UnwashedMeme/sudoku<file_sep>/sudoku.py
from StringIO import StringIO
import re, traceback, types, itertools
import cProfile, pstats, time
import logging
from copy import deepcopy, copy
import puzzles, puzzles2
logging.basicConfig(level=logging.info)
PVALS = set(range(1,10))
PIDXS = set(range(0,9))
class Index (object):
def __init__(self,row,col):
self.row,self.col = row,col
def __eq__(self, other):
return self.row == other.row and self.col == other.col
def __str__(self):
return "<%s,%s>"%(self.row, self.col)
def __repr__(self):
return "<%s,%s>"%(self.row, self.col)
def __hash__(self):
return self.row*100+self.col
def __iter__(self):
yield self.row
yield self.col
def cross(l1, l2):
return [Index(i,j) for i in l1 for j in l2]
puzzle_range = cross(PIDXS,PIDXS)
def tryint(v):
try: return int(v)
except: return None
class Memoize(object):
"""Memoize(fn) - an instance which acts like fn but memoizes its arguments
Will only work on functions with non-mutable arguments
"""
def __init__(self, fn):
self.fn = fn
self.memo = {}
def __call__(self, *args):
if not self.memo.has_key(args):
self.memo[args] = self.fn(*args)
return self.memo[args]
class PosCount(object):
def __init__(self, cnt=0, idxs=None):
self.cnt,self.idxs=cnt,idxs or []
def __repr__(self):
return "|%d|"%self.cnt
def __str__(self):
return "|%d|"%self.cnt
def square_idxs(i):
r = i / 3
return range(r*3,r*3+3)
def square(idx):
return cross(square_idxs(idx.row), square_idxs(idx.col))
class NoPossibleValues(Exception):
def __init__(self, row=None, col=None):
self.row,self.col = row,col
def __str__(self):
return "NoPossibleValues for <%s,%s>" % (self.row, self.col)
class Box (object):
def __init__(self, idx, val):
self.idx,self.val = idx,val
def __len__(self):
if isinstance(self.val,int): return 1
elif not self.val: return 0
return len(self.val)
def __str__(self):
return "Box(%s,%s)"%(self.idx,self.val)
class Stats (object):
def __init__(self,**kws):
for k,v in kws.items():
setattr(self, k, v)
def inc(self,k,v=1):
return setattr(self, k, getattr(self,k,0)+v)
class Sudoku (object):
def __init__(self, puzzle, parent=None, depth=1,
start=None, unsolved_idxs=None,
stats=None):
self.stats = stats or Stats(puzzle_branches=1, constraint_steps=0)
self.puzzle = puzzle
self.parent = parent
self.depth = depth
self.unsolved_idxs = unsolved_idxs or deepcopy(puzzle_range)
self.start = start or time.time()
self.ip = Memoize(Sudoku.index_possibilities)
self.index_possibilities = types.MethodType(self.ip, self, Sudoku)
def make_child(self, box=None, new_val=None):
self.stats.puzzle_branches+=1
idx = self.stats.puzzle_branches
if idx%1000==0:
print "Making branch (idx:%d, depth:%d): %s val:%s - %ss" % \
(idx, self.depth, box, new_val, time.time()-self.start)
c = Sudoku(deepcopy(self.puzzle), self, self.depth+1, self.start, \
deepcopy(self.unsolved_idxs), self.stats)
if box and new_val:
c.puzzle[box.idx.row][box.idx.col] = new_val
return c
def open_boxes(self):
return sorted([Box(idx,self.index_possibilities(idx))
for idx in puzzle_range
if not self.square_solved(idx)],
key=len)
def search(self):
try:
self.constrain()
except NoPossibleValues,e:
if self.parent: raise e
else:
print "ERROR ON BOARD:\n",self
raise e
if self.is_solved(): return self
logging.warning("Couldn't solve board via constraints, %s\nStarting to guess",self)
# really only care about the first open box as it WILL be one
# of the values there if our model is correct up till now
# otherwise any mistake is enough to backtrack
box = self.open_boxes()[0]
for v in box.val or []:
try:
c = self.make_child(box, v)
sol = c.search()
if sol: return sol
except NoPossibleValues,e: pass
def solve(self):
sol = self.search()
if sol and sol.is_solved():
#self.puzzle = deepcopy(sol.puzzle)
sol.status()
else:
print self
raise Exception("Puzzle Not Solved...")
return sol
def square_solved(self,idx):
return self.puzzle[idx.row][idx.col]
def clear_puzzle_possibility_cache(self):
self.ip.memo={} #reset IP memoization
def set_puzzle_val(self, idx, v):
self.clear_puzzle_possibility_cache()
self.puzzle[idx.row][idx.col] = v
self.unsolved_idxs.remove(idx)
def constrain(self):
new_constraint = False
constraints = [
self.naked_sets_exclusion_in_col,
self.naked_sets_exclusion_in_square,
self.naked_sets_exclusion_in_row,
self.unique_possibility_in_row,
self.unique_possibility_in_col,
self.unique_possibility_in_square,
self.xwing_col_constraint,
self.xwing_row_constraint,
# These seem to be not constraing over the others
self.squeeze_col,
self.squeeze_row,
]
def fn():
self._constrained_this_cycle = False
for cons in constraints:
# copy the set so we can remove the currently inspected index if nec
for idx in list(self.unsolved_idxs):
self.stats.constraint_steps+=1
if self.square_solved(idx):
self.unsolved_idxs.remove(idx)
continue
p = self.index_possibilities(idx)
if len(p)==1: self.stats.inc('single_possibility')
elif len(p)>1: p = cons(p, idx)
# start over reconstraining
if len(p)==1:
self.set_puzzle_val(idx,p.pop())
return True
elif len(p)==0: raise NoPossibleValues(idx)
return self._constrained_this_cycle
while(fn()): pass
def free_in_row(self, row):
return [idx
for j in PIDXS
for idx in [Index(row,j)]
if not self.square_solved(idx)]
def free_in_col(self, col):
return [idx
for i in PIDXS
for idx in [Index(i,col)]
if not self.square_solved(idx)]
def free_in_square(self, idx_in):
return [idx
for idx in square(idx_in)
if not self.square_solved(idx)]
def free_related_cells(self, idx):
return self.free_in_row(idx.row)+self.free_in_col(idx.col)+self.free_in_square(idx)
def free_related_possibilities(self, idx):
return [self.index_possibilities(i)
for i in self.free_related_cells(idx)
if i!=idx]
def closed_square_row(self, idx):
return [i for i in square_idxs(idx.row)
if self.square_solved(Index(i, idx.col))]
def closed_square_col(self, idx):
return [j for j in square_idxs(idx.col)
if self.square_solved(Index(idx.row, j))]
def is_in_row(self, val, row):
for j in PIDXS:
if self.puzzle[row][j] == val: return True
def is_in_col(self, val, col):
for i in PIDXS:
if self.puzzle[i][col] == val: return True
def xwing_row_constraint(self, pos, idx):
posCounts = [[PosCount() for i in range(0,9)]
for i in range(0,9)]
for i in self.unsolved_idxs:
for val in self.index_possibilities(i):
posCounts[i.row][val-1].cnt+=1
posCounts[i.row][val-1].idxs.append(i)
p = deepcopy(pos)
for val in p:
i1=None
i2=None
for i in PIDXS:
if i!=idx.row and posCounts[i][val-1].cnt==2: # 2 cells share this pos
if i1: i2=i
else: i1=i
if i1 and i2:
c1,c2 = posCounts[i1][val-1].idxs
c3,c4 = posCounts[i2][val-1].idxs
if c1.col>c2.col: c1,c2 = c2,c1
if c3.col>c4.col: c3,c4 = c4,c3
if c1.col!=c3.col or c2.col!=c4.col: continue # not an xwing square
if c1.col!=idx.col and c2.col!=idx.col: continue # not relevant to me
# we have an xwing square
pos = pos - set([val])
if len(pos) == 1 :
#print "XWING : <%s,%s> to %s\n" % (row,col,pos)
#print c1, self.index_possibilities(*c1)
#print c2, self.index_possibilities(*c2)
#print c3, self.index_possibilities(*c3)
#print c4, self.index_possibilities(*c4)
self.stats.inc('xwing_row')
return pos
return pos
def xwing_col_constraint(self, pos, idx):
posCounts = [[PosCount() for i in range(0,9)]
for i in range(0,9)]
for i in self.unsolved_idxs:
for val in self.index_possibilities(idx):
posCounts[i.col][val-1].cnt+=1
posCounts[i.col][val-1].idxs.append(i)
p = deepcopy(pos)
for val in p:
j1=None
j2=None
for j in PIDXS:
if j!=idx.col and posCounts[j][val-1].cnt==2: # 2 cells share this pos
if j1: j2=j
else: j1=j
if j1 and j2:
c1,c2 = posCounts[j1][val-1].idxs
c3,c4 = posCounts[j2][val-1].idxs
if c1.col>c2.col: c1,c2 = c2,c1
if c3.col>c4.col: c3,c4 = c4,c3
if c1.col!=c3.col or c2.col!=c4.col: continue # not an xwing square
if c1.col!=idx.col and c2.col!=idx.col: continue # not relevant to me
# we have an xwing square
pos = pos - set([val])
if len(pos) == 1 :
self.stats.inc('xwing_col')
return pos
return pos
def squeeze_col(self, pos, idx):
""" constrain possibilities by squeezing
http://www.chessandpoker.com/sudoku-strategy-guide.html
"""
if len(self.closed_square_col(idx))==2: # two closed columns
idxs = square_idxs(idx.row)
idxs.remove(idx.row)
for v in pos:
if self.is_in_row(v, idxs[0]) and self.is_in_row(v,idxs[1]):
#print "Squeezing <%s,%s> to %s" % (row, col, v)
self.stats.inc('squeeze_col')
return set([v])
return pos
def squeeze_row(self, pos, idx):
if len(self.closed_square_row(idx))==2: # two closed rows
idxs = square_idxs(idx.col)
idxs.remove(idx.col)
for v in pos:
if self.is_in_col(v, idxs[0]) and self.is_in_col(v,idxs[1]):
#print "Squeezing <%s,%s> to %s" % (row, col, v)
self.stats.inc('squeeze_row')
return set([v])
return pos
def _unique_possibility_helper(self, cells, pos, name):
for v in pos:
not_allowed_elsewhere = \
all(not v in self.index_possibilities(i)
for i in cells)
if not_allowed_elsewhere:
self.stats.inc(name)
return set([v])
return pos
def unique_possibility_in_square(self,pos,idx):
""" constrain possibilities by crosshatching
http://www.chessandpoker.com/sudoku-strategy-guide.html
"""
cells = self.free_in_square(idx)
cells.remove(idx)
return self._unique_possibility_helper( cells, pos, 'unique_in_square')
def unique_possibility_in_row(self,pos,idx):
""" constrain possibilities by crosshatching
http://www.chessandpoker.com/sudoku-strategy-guide.html
"""
cells = self.free_in_row(idx.row)
cells.remove(idx)
return self._unique_possibility_helper(cells, pos, 'unique_in_row')
def unique_possibility_in_col(self,pos,idx):
cells = self.free_in_col(idx.col)
cells.remove(idx)
return self._unique_possibility_helper(cells, pos, 'unique_in_col')
def _naked_sets_helper(self, free_list, pos, name):
free_list.sort(key=self.index_possibilities)
# naked sets
groups = [(i,gl)
for i,g in itertools.groupby(free_list, self.index_possibilities)
for gl in [list(g)]]
kfn = lambda x: len(x[0])
groups.sort(key=kfn)
naked_groups=[]
not_naked = []
for i1, gl1 in groups:
if len(i1) == len(gl1) and len(i1) > 1 :
naked_groups.append((i1,gl1))
else:
not_naked.append((i1,gl1))
def fn():
ahead = 1
not_naked.sort(key=kfn)
for i1,gl1 in not_naked:
for i2, gl2 in not_naked[ahead:]:
if i1 <= i2: #subset
# the intersection of the possibilities is the length of the indexes
if len(gl1)+len(gl2) == len(i2):
not_naked.remove((i1,gl1))
not_naked.remove((i2,gl2))
naked_groups.append((i2,gl1+gl2))
self.stats.inc(name+'_complex_constraint')
return True
else:
not_naked.remove((i1,gl1))
not_naked.remove((i2,gl2))
not_naked.append((i2,gl1+gl2))
return True
ahead +=1
while(fn()):pass
# handle hidden sets -- never triggering currently
for i, gl in not_naked:
if len(gl) <= 2: continue # cant be hidden
p = [self.index_possibilities(x) for x in gl]
p.sort(key=len)
maxp = p[-1] # longest pos list
shared = p[1] # shortest pos list
for p in p[1:-1]: shared = shared & p # union the rest of the short lists together
shared = maxp | shared # remove all the shared items from the longest pos list
if len(shared) == len(gl): # if we only share as many pos as cells
self.stats.append('hidden_set_constraint')
self.naked_groups.add((shared,gl))
self.not_naked.remove((i,gl))
for p in [self.index_possibilities(x)
for x in gl]:
for v in list(p):
if v not in shared:
p.remove(v)
# if we know these possiblities are being
# used up in the naked set, might as well remove them
# from everyone elses possibilities
for not_pos,gl in naked_groups:
for cell in free_list:
if not cell in gl:
to_tell = self.index_possibilities(cell)
for i in not_pos:
if i in to_tell:
self._constrained_this_cycle=True
self.stats.inc(name+'_contraint')
to_tell.remove(i)
# if I want to resolve the current square based on this I should uncomment,
# but i want it to work just by removing possibilities now
# if len(groups)>0:
# # print "NAKED COL SET", groups
# for not_pos, idxs in groups:
# p = pos - not_pos
# if len(p)==1:
# self.stats.inc(name)
# return p
return pos
def naked_sets_exclusion_in_col(self,pos,idx):
fic = self.free_in_col(idx.col)
fic.remove(idx)
return self._naked_sets_helper(fic,pos,'naked_sets_col')
def naked_sets_exclusion_in_row(self,pos,idx):
fic = self.free_in_row(idx.row)
fic.remove(idx)
return self._naked_sets_helper(fic,pos,'naked_sets_row')
def naked_sets_exclusion_in_square(self,pos,idx):
fic = self.free_in_square(idx)
fic.remove(idx)
return self._naked_sets_helper(fic,pos,'naked_sets_square')
def index_constraints(self,idx):
knowns = set()
for i in PIDXS: knowns.add( self.puzzle[i][idx.col] )
for i in PIDXS: knowns.add( self.puzzle[idx.row][i] )
for i,j in square(idx): knowns.add( self.puzzle[i][j] )
knowns.remove(None) # avoids many ifs
return knowns
def index_possibilities(self,idx):
v = self.square_solved(idx)
if v: return set([v])
pos = PVALS - self.index_constraints(idx)
return pos
def is_solved(self):
for i in puzzle_range:
if not self.square_solved(i): return False
return self
def status(self):
s=StringIO()
if self.is_solved():
s.write('Solved Puzzle: \n')
else:
s.write('Unsolved Puzzle:\n')
stats = deepcopy(vars(self.stats))
del stats['constraint_steps']
del stats['puzzle_branches']
s.write(" %s - Constraint Cycles\n" % self.stats.constraint_steps)
s.write(" %s - Branches\n\n" % self.stats.puzzle_branches)
items = stats.items()
items.sort()
for k,v in items:
s.write(' %s : %s \n' % (k,v))
s = s.getvalue()
logging.info(s)
return s
def __str__(self):
s = StringIO()
s.write("-------------------------------\n")
s.write(self.status())
s.write("-------------------------------\n")
for i in PIDXS:
s.write('|')
for j in PIDXS:
s.write(' ')
if self.square_solved(Index(i,j)): s.write(self.puzzle[i][j])
else: s.write( '.' )
s.write(' ')
if j%3==2: s.write('|')
s.write('\n')
if i%3==2: s.write("-------------------------------\n")
return s.getvalue()
def read_puzzle (s):
puzzle = [[None for j in PIDXS]
for i in PIDXS]
#skip first/last line
s = re.sub(r'\n\n+','\n',re.sub(r'-|\+|\|| |,',"",s))
partial_sol = s.splitlines()[1:]
i,j=0,0
for row in partial_sol:
j=0
if i>8: continue
for char in row:
#print i,j,char
if j>8: continue
puzzle[i][j] = tryint(char)
j+=1
i+=1
return Sudoku(puzzle)
PUZZLE = read_puzzle(puzzles.puzzles[0])
def solve_puzzle(s):
global PUZZLE
if isinstance(s,str):
s = read_puzzle(s)
p = s.solve()
assert p.is_solved()
PUZZLE = p
return p
def solve_some_puzzles():
i = 1
total_time = 0
for p in puzzles2.puzzles:
print "Starting puzzle %s" % i
p = read_puzzle(p)
p.start = time.time()
s = solve_puzzle(p)
print s
ptime = time.time()-p.start
total_time += ptime
print "Done with puzzle %s in %s sec" % (i, ptime)
i+=1
print "Done with %d puzzles in %s sec" % (len(puzzles2.puzzles), total_time)
if __name__ == "__main__":
solve_some_puzzles()
else:
try:
pf = 'sudoku.v4'
cProfile.run('sudoku.solve_some_puzzles()', pf)
p = pstats.Stats(pf)
p.strip_dirs().sort_stats(-1)
p.sort_stats('time').print_stats(10)
except NameError,e:
print "Reload module to run profiling"
traceback.print_exc();
except Exception, e:
traceback.print_exc();
|
4e43b54bc652bcb0cd92caa6eee8500231004ee6
|
[
"Python"
] | 1
|
Python
|
UnwashedMeme/sudoku
|
a38144802e4208e82ac587178648dfb80ae1e9a1
|
aa66e380f8cb2d86345647d8ca90cea9a596486f
|
refs/heads/main
|
<repo_name>asalam345/mymedicalhub<file_sep>/CRUDAspNetCore5WebAPI/Entity/Domains/PatientSchedule.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace Domains
{
[Table("PatientSchedule", Schema = "dbo")]
public class PatientSchedule
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[Display(Name = "Patient Id")]
public int PatientId { get; set; }
[Required]
[Display(Name = "Doctor Id")]
public int DoctorId { get; set; }
[Required]
[Display(Name = "UserEmail")]
public string UserEmail { get; set; }
[Required]
[Display(Name = "Created On")]
public DateTime CreatedOn { get; set; } = DateTime.Now;
[Required]
[Display(Name = "Schedule Date")]
public DateTime ScheduleDate { get; set; }
[Required]
[Display(Name = "IsMeet")]
public bool IsDeleted { get; set; } = false;
}
}
<file_sep>/Project/UI/UI/Models/UserData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UI.Models
{
public class UserVM
{
public string emailOrMobile { get; set;}
public string password { get; set; }
}
}
<file_sep>/CRUDAspNetCore5WebAPI/AspNetCoreWebAPI/Controllers/DoctorController.cs
using Manager.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AspNetCoreWebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Consumes("application/json")]
[Authorize(roles: "Doctor")]
public class DoctorController : ControllerBase
{
[HttpGet]
public Object Get()
{
List<string> doctors = new List<string>()
{
"Ahmad",
"<NAME>",
"<NAME>"
};
var json = JsonConvert.SerializeObject(doctors, Formatting.Indented,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return json;
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Interfaces/Service/IUserService.cs
using Domains;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using ViewModels;
namespace Interfaces.Service
{
public interface IUserService
{
SignUpUserVM GetUserByUserId(int userId);
IEnumerable<SignUpUserVM> GetAllUsers();
SignUpUserVM GetUserByEmailOrMobileAndPassword(string email, string mobile, string password);
Task<SignUpUserVM> AddUser(SignUpUserVM userVm);
Task<RegConfirmationVM> AddCode(RegConfirmationVM regCon);
bool DeviceConfirm(RegConfirmationVM regCon);
bool DeleteUser(string UserEmail);
bool UpdateUser(SignUpUserVM userVM);
SignUpUserVM GetUserByEmailOrMobile(string emailOrMobile, bool isEmail);
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Manager/Converter/UserConverter.cs
using Domains;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewModels;
namespace Manager.Converter
{
public class UserConverter
{
public static List<SignUpUserVM> FromUser(List<User> list)
{
List<SignUpUserVM> vmList = new List<SignUpUserVM>();
foreach (User s in list)
{
SignUpUserVM vm = new SignUpUserVM();
vm.Id = s.Id;
vm.Email = s.Email;
vm.Mobile = s.Mobile;
vm.FullName = s.FullName;
vm.Password = <PASSWORD>;
vmList.Add(vm);
}
return vmList;
}
public static List<User> FromUserVM(List<SignUpUserVM> vmList)
{
List<User> list = new List<User>();
foreach (SignUpUserVM vm in vmList)
{
User s = new User();
s.Id = vm.Id;
s.Email = vm.Email;
s.Mobile = vm.Mobile;
s.FullName = vm.FullName;
s.Password = <PASSWORD>;
s.IsEmailConfirm = vm.IsEmailConfirm;
list.Add(s);
}
return list;
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Entity/ViewModels/RegiterConfirmationVM.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ViewModels
{
public class RegConfirmationVM
{
public int Id { get; set; }
public int UserId { get; set; }
public char Device { get; set; }
public string Code { get; set; }
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Entity/Domains/Prescription.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace Domains
{
public class Prescription
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[Display(Name = "Schedule Id")]
public int ScheduleId { get; set; }
[Required]
[Display(Name = "Schedule Id")]
public string Description { get; set; }
[Display(Name = "Report Id")]
public int ReportId { get; set; } = 0;
public string Comment { get; set; }
}
}
<file_sep>/Project/UI/UI/Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using UI.Models;
namespace UI.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
[HttpPost]
public JsonResult Login(string user, string password)
{
string apiUrl = "UserDetails";// /LoginUser
UserVM ud = new UserVM { emailOrMobile= user, password = <PASSWORD> };
DataTable responseObj = ApiCall.PostInfo(ud, apiUrl).Result;
return Json(new { name="", role= ""});
}
public async Task<ActionResult> Index()
{
ViewBag.User = null;
string apiUrl = "https://localhost:44362/api/UserDetails/GetAllUsers";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
//Stream receiveStream = response.GetResponseStream();
var data = await response.Content.ReadAsStringAsync();
//StreamReader readStream = new StreamReader(data, Encoding.UTF8);
//var table = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(data);
//return Json(data);
var newString = data.Replace(@"\r\n", "");
ViewBag.User = newString;
}
}
return View();
}
public IActionResult Calendar()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Manager/Authorization/IsUserValid.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using ViewModels;
namespace Manager.Authorization
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class IsUserValid : Attribute, IAuthorizationFilter
{
public IsUserValid()
{
}
public void OnAuthorization(AuthorizationFilterContext context)
{
// skip authorization if action is decorated with [AllowAnonymous] attribute
var allowAnonymous = context.ActionDescriptor.EndpointMetadata.OfType<AllowAnonymousAttribute>().Any();
if (allowAnonymous)
return;
// authorization
var user = (SignUpUserVM)context.HttpContext.Items["User"];
if (user == null || user.IsDelete || (!user.IsEmailConfirm && !user.IsMobileConfirm))
{
// not logged in or role not authorized
context.Result = new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized };
}
}
}
}<file_sep>/CRUDAspNetCore5WebAPI/Interfaces/Repository/IUser.cs
using Domains;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Interfaces.Repository
{
public interface IUser
{
User IsExists(User user);
bool IsCodeExists(RegConfirmation regCon);
Task<RegConfirmation> Create(RegConfirmation regCon);
RegConfirmation Update(RegConfirmation regCon);
object GetUserWithRole(int? userId, string email, string mobile, string password);
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Manager/Converter/RoleEnrollmentConverter.cs
using Domains;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewModels;
namespace Manager.Converter
{
public class RoleEnrollmentConverter
{
public static List<RoleEnrollmentVM> FromRoleEnrollment(List<RoleEnrollment> list)
{
List<RoleEnrollmentVM> vmList = new List<RoleEnrollmentVM>();
foreach (RoleEnrollment s in list)
{
RoleEnrollmentVM vm = new RoleEnrollmentVM();
vm.Id = s.Id;
vm.UserId = s.UserId;
vm.RoleId =s.RoleId;
vmList.Add(vm);
}
return vmList;
}
public static List<RoleEnrollment> FromRoleEnrollmentVM(List<RoleEnrollmentVM> vmList)
{
List<RoleEnrollment> list = new List<RoleEnrollment>();
foreach (RoleEnrollmentVM vm in vmList)
{
RoleEnrollment s = new RoleEnrollment();
s.Id = vm.Id;
s.UserId = vm.UserId;
s.RoleId = vm.RoleId;
list.Add(s);
}
return list;
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Interfaces/Service/IRoleEnrollService.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using ViewModels;
namespace Interfaces.Service
{
public interface IRoleEnrollService
{
IEnumerable<RoleEnrollmentVM> GetRoleEnrollmentByRoleEnrollmentId(int userId);
IEnumerable<RoleEnrollmentVM> GetAllRoleEnrollments();
Task<RoleEnrollmentVM> AddRoleEnrollment(RoleEnrollmentVM RoleEnrollment);
bool DeleteRoleEnrollment(int id);
bool UpdateRoleEnrollment(RoleEnrollmentVM user);
}
}
<file_sep>/CRUDAspNetCore5WebAPI/AspNetCoreWebAPI/Controllers/UserController.cs
using Domains;
using Interfaces.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ViewModels;
namespace CRUDAspNetCore5WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly IUserService _userService;
private readonly IRoleEnrollService _roleEnrollService;
public UserController(IUserService userService, IRoleEnrollService roleEnrollService)
{
_userService = userService;
_roleEnrollService = roleEnrollService;
}
//Delete User
[HttpDelete("DeleteUser")]
public bool DeleteUser(string UserEmail)
{
try
{
_userService.DeleteUser(UserEmail);
return true;
}
catch (Exception)
{
return false;
}
}
//Delete User
[HttpPut("UpdateUser")]
public bool UpdateUser(SignUpUserVM userVM)
{
try
{
_userService.UpdateUser(userVM);
return true;
}
catch (Exception)
{
return false;
}
}
//GET All User
[HttpGet("GetAllUsers")]
public Object GetAllUsers()
{
var data = _userService.GetAllUsers();
var json = JsonConvert.SerializeObject(data, Formatting.Indented,
new JsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
}
);
return json;
}
}
}<file_sep>/CRUDAspNetCore5WebAPI/DAL/Data/ApplicationDbContext.cs
using Domains;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace DAL.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public DbSet<User> Users { get; set; }
public DbSet<PatientSchedule> PatientSchedules { get; set; }
public DbSet<PatientType> PatientTypes { get; set; }
public DbSet<PatientTypeEnrollment> PatientTypeEnrollments { get; set; }
public DbSet<Prescription> Prescriptions { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<RoleEnrollment> RoleEnrollments { get; set; }
public DbSet<RegConfirmation> RegConfirmations { get; set; }
}
}
<file_sep>/CRUDAspNetCore5WebAPI/DAL/Repository/RepositoryRole.cs
using DAL.Data;
using Domains;
using Interfaces.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL.Repository
{
public class RepositoryRole : IRepository<Role>
{
ApplicationDbContext _dbContext;
public RepositoryRole(ApplicationDbContext applicationDbContext)
{
_dbContext = applicationDbContext;
}
public async Task<Role> Create(Role _object)
{
var obj = await _dbContext.Roles.AddAsync(_object);
_dbContext.SaveChanges();
return obj.Entity;
}
public void Delete(Role _object)
{
_dbContext.Remove(_object);
_dbContext.SaveChanges();
}
public IEnumerable<Role> GetAll()
{
try
{
return _dbContext.Roles.ToList();
}
catch (Exception e)
{
throw;
}
}
public Role GetById(int id)
{
return _dbContext.Roles.Where(x => x.Id == id).FirstOrDefault();
//return _dbContext.RoleEnrollments.Where(x => x.UserId == id).Join(_dbContext.Roles, e => e.RoleId, r => r.Id, (e, r) => new Role { r.Title, r.Id}).FirstOrDefault();
}
public void Update(Role _object)
{
_dbContext.Roles.Update(_object);
_dbContext.SaveChanges();
}
}
}
<file_sep>/Project/UI/UI/Models/ApiCall.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading.Tasks;
namespace UI.Models
{
public class ApiCall
{
public static async Task<DataTable> PostInfo(UserVM requestObj, string extention)
{
// Initialization.
DataTable responseObj = new DataTable();
// Posting.
using (var client = new HttpClient())
{
string url = "https://localhost:44362/api/";
// Setting Base address.
client.BaseAddress = new Uri(url);
// Setting content type.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Initialization.
HttpResponseMessage response = new HttpResponseMessage();
// HTTP POST
//response = await client.PostAsJsonAsync(extention, requestObj).ConfigureAwait(false);
//HttpClient c = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true });
//response = await client.PostAsJsonAsync(extention + "?emailOrMobile=" + requestObj.emailOrMobile + "?password=" + requestObj.password, null).ConfigureAwait(false); // returns 200
// Verification
if (response.IsSuccessStatusCode)
{
// Reading Response.
string result = response.Content.ReadAsStringAsync().Result;
responseObj = JsonConvert.DeserializeObject<DataTable>(result);
}
}
//HttpClient c = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true });
//var x = c.PostAsync("https://localhost:44362/api/values?emailOrMobile=" + "test", sc).Result; // returns 200
return responseObj;
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/AspNetCoreWebAPI/Controllers/DashboardController.cs
using Manager.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ViewModels;
namespace CRUDAspNetCore5WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Consumes("application/json")]
[IsUserValid]
public class DashboardController : ControllerBase
{
[HttpGet("page")]
public Object page()
{
var data = new string[2];
var currentUser = (SignUpUserVM)HttpContext.Items["User"];
data[0] = currentUser.FullName;
string role = currentUser.RoleModel.Title;
switch (role)
{
case "Doctor":
data[1] = "Doctor";
break;
case "Patient":
data[1] = "Patient";
break;
default: return Ok("This Secured Data is available only for Authenticated Users.");
}
var json = JsonConvert.SerializeObject(data, Formatting.Indented,
new JsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
}
);
return json;
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/DAL/Repository/RepositoryUser.cs
using DAL.Data;
using Domains;
using Interfaces.Repository;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL.Repository
{
public class RepositoryUser : IRepository<User>, IUser
{
ApplicationDbContext _dbContext;
public RepositoryUser(ApplicationDbContext applicationDbContext)
{
_dbContext = applicationDbContext;
}
public async Task<User> Create(User _object)
{
var obj = await _dbContext.Users.AddAsync(_object);
_dbContext.SaveChanges();
if (obj.Entity.Id > 0)
{
return obj.Entity;
}
return null;
}
public void Delete(User _object)
{
_dbContext.Remove(_object);
_dbContext.SaveChanges();
}
public IEnumerable<User> GetAll()
{
try
{
return _dbContext.Users.Where(x => x.IsDeleted == false).AsNoTracking().ToList();
}
catch (Exception ex)
{
throw;
}
}
public User GetById(int Id)
{
return _dbContext.Users.Where(x => x.IsDeleted == false && x.Id == Id).AsNoTracking().FirstOrDefault();
}
public void Update(User _object)
{
_dbContext.Users.Update(_object);
_dbContext.SaveChanges();
}
public User IsExists(User user)
{
return _dbContext.Users.Where(x => x.Email == user.Email || x.Mobile == user.Mobile).AsNoTracking().FirstOrDefault();
}
public bool IsCodeExists(RegConfirmation regCon)
{
var row = _dbContext.RegConfirmations.Where(w => w.UserId == regCon.UserId && w.Device == regCon.Device && w.Code == regCon.Code).AsNoTracking().FirstOrDefault();
if (row == null) return false;
return true;
}
public async Task<RegConfirmation> Create(RegConfirmation regCon)
{
try
{
var obj = await _dbContext.RegConfirmations.AddAsync(regCon);
_dbContext.SaveChanges();
return obj.Entity;
}
catch (Exception ex)
{
return null;
}
}
public RegConfirmation Update(RegConfirmation regCon)
{
try
{
var obj = _dbContext.RegConfirmations.Update(regCon);
_dbContext.SaveChanges();
return obj.Entity;
}
catch (Exception ex)
{
return null;
}
}
public object GetUserWithRole(int? userId, string email, string mobile, string password)
{
var query = from u in _dbContext.Users
join r in _dbContext.RoleEnrollments on u.Id equals r.UserId
join e in _dbContext.Roles on r.RoleId equals e.Id
where (userId != null ? u.IsDeleted == false && u.Id == userId : u.IsDeleted == false &&
(u.Email == email && u.IsEmailConfirm == true) ||
(u.Mobile == mobile && u.IsMobileConfirm == true) && u.Password == <PASSWORD>)
select new
{
u.Id,
u.Email,
u.IsEmailConfirm,
e.Title
};
//select new
//{
// Id = u.Id,
// Email = u.Email,
// Mobile = u.Mobile,
// FullName = u.FullName,
// Password = <PASSWORD>,
// UserRole = e.Id,
// RoleName = e.Title,
// IsEmailConfirm = u.IsEmailConfirm,
// IsMobileConfirm = u.IsMobileConfirm
//});
//SignUpUserVM data = query.FirstOrDefault();
return query.FirstOrDefault();
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/DAL/Migrations/20211008112625_3rdInit.cs
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace DAL.Migrations
{
public partial class _3rdInit : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "PatientSchedule",
schema: "dbo",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PatientId = table.Column<int>(type: "int", nullable: false),
DoctorId = table.Column<int>(type: "int", nullable: false),
UserEmail = table.Column<string>(type: "nvarchar(max)", nullable: false),
CreatedOn = table.Column<DateTime>(type: "datetime2", nullable: false),
ScheduleDate = table.Column<DateTime>(type: "datetime2", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PatientSchedule", x => x.Id);
});
migrationBuilder.CreateTable(
name: "PatientType",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Title = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PatientType", x => x.Id);
});
migrationBuilder.CreateTable(
name: "PatientTypeEnrollment",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<int>(type: "int", nullable: false),
PatientTypeId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PatientTypeEnrollment", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Prescriptions",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ScheduleId = table.Column<int>(type: "int", nullable: false),
Description = table.Column<string>(type: "nvarchar(max)", nullable: false),
ReportId = table.Column<int>(type: "int", nullable: false),
Comment = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Prescriptions", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Role",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Title = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Role", x => x.Id);
});
migrationBuilder.CreateTable(
name: "RoleEnrollment",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<int>(type: "int", nullable: false),
RoleId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RoleEnrollment", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "PatientSchedule",
schema: "dbo");
migrationBuilder.DropTable(
name: "PatientType");
migrationBuilder.DropTable(
name: "PatientTypeEnrollment");
migrationBuilder.DropTable(
name: "Prescriptions");
migrationBuilder.DropTable(
name: "Role");
migrationBuilder.DropTable(
name: "RoleEnrollment");
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Interfaces/Utility/IMailService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewModels;
namespace Interfaces.Utility
{
public interface IMailService
{
Task SendEmailAsync(MailRequest mailRequest);
Task SendConfirmationEmailAsync(SignUpUserVM request, string code);
bool EmailIsValid(string email);
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Entity/Domains/RoleEnrollment.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace Domains
{
public class RoleEnrollment
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[Display(Name = "User Id")]
public int UserId { get; set; }
[Required]
[Display(Name = "Role Id")]
public int RoleId { get; set; }
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Manager/Utility/RandomService.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace Manager.Utility
{
public class RandomService
{
//private readonly Random _random = new Random();
//// Generates a random number within a range.
//public int RandomNumber(int min, int max)
//{
// return _random.Next(min, max);
//}
public static string RandomPassword(int cLength = 2, int lLength = 2,
int dLength = 4, int scLength = 2,
bool needCap = false,
bool needLow = false,
bool needSpecial = false)
{
Random ran = new Random();
String random = "";
String d = "0123456789";
String c = "ABCDEFGHJKLMNPQRSTUVWXYZ";
String l = "abcdefghijklmnopqrstuvwxyz";
String sc = "!@#$%^&*~";
for (int i = 0; i < dLength; i++)
{
int a = ran.Next(d.Length); //string.Lenght gets the size of string
random = random + d.ElementAt(a);
}
if (needCap)
{
for (int i = 0; i < cLength; i++)
{
int a = ran.Next(c.Length); //string.Lenght gets the size of string
random = random + c.ElementAt(a);
}
}
if (needLow)
{
for (int i = 0; i < lLength; i++)
{
int a = ran.Next(l.Length); //string.Lenght gets the size of string
random = random + l.ElementAt(a);
}
}
if (needSpecial)
{
for (int i = 0; i < scLength; i++)
{
int a = ran.Next(sc.Length);
random = random + sc.ElementAt(a);
}
}
return random;
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Interfaces/Repository/IRepository.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Interfaces.Repository
{
public interface IRepository<T>
{
Task<T> Create(T _object);
void Update(T _object);
IEnumerable<T> GetAll();
T GetById(int Id);
void Delete(T _object);
}
}<file_sep>/CRUDAspNetCore5WebAPI/DAL/Migrations/20211008120413_5thInit.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace DAL.Migrations
{
public partial class _5thInit : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_RoleEnrollment",
table: "RoleEnrollment");
migrationBuilder.DropPrimaryKey(
name: "PK_Role",
table: "Role");
migrationBuilder.DropPrimaryKey(
name: "PK_PatientTypeEnrollment",
table: "PatientTypeEnrollment");
migrationBuilder.DropPrimaryKey(
name: "PK_PatientType",
table: "PatientType");
migrationBuilder.RenameTable(
name: "RoleEnrollment",
newName: "RoleEnrollments");
migrationBuilder.RenameTable(
name: "Role",
newName: "Roles");
migrationBuilder.RenameTable(
name: "PatientTypeEnrollment",
newName: "PatientTypeEnrollments");
migrationBuilder.RenameTable(
name: "PatientType",
newName: "PatientTypes");
migrationBuilder.AddPrimaryKey(
name: "PK_RoleEnrollments",
table: "RoleEnrollments",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_Roles",
table: "Roles",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_PatientTypeEnrollments",
table: "PatientTypeEnrollments",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_PatientTypes",
table: "PatientTypes",
column: "Id");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropPrimaryKey(
name: "PK_Roles",
table: "Roles");
migrationBuilder.DropPrimaryKey(
name: "PK_RoleEnrollments",
table: "RoleEnrollments");
migrationBuilder.DropPrimaryKey(
name: "PK_PatientTypes",
table: "PatientTypes");
migrationBuilder.DropPrimaryKey(
name: "PK_PatientTypeEnrollments",
table: "PatientTypeEnrollments");
migrationBuilder.RenameTable(
name: "Roles",
newName: "Role");
migrationBuilder.RenameTable(
name: "RoleEnrollments",
newName: "RoleEnrollment");
migrationBuilder.RenameTable(
name: "PatientTypes",
newName: "PatientType");
migrationBuilder.RenameTable(
name: "PatientTypeEnrollments",
newName: "PatientTypeEnrollment");
migrationBuilder.AddPrimaryKey(
name: "PK_Role",
table: "Role",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_RoleEnrollment",
table: "RoleEnrollment",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_PatientType",
table: "PatientType",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_PatientTypeEnrollment",
table: "PatientTypeEnrollment",
column: "Id");
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Manager/Converter/RegConfirmationConverter.cs
using Domains;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewModels;
namespace Manager.Converter
{
public class RegConfirmationConverter
{
public static List<RegConfirmationVM> FromRegConfirmation(List<RegConfirmation> list)
{
List<RegConfirmationVM> vmList = new List<RegConfirmationVM>();
foreach (RegConfirmation s in list)
{
RegConfirmationVM vm = new RegConfirmationVM();
vm.Id = s.Id;
vm.UserId = s.UserId;
vm.Device =s.Device;
vm.Code = s.Code;
vmList.Add(vm);
}
return vmList;
}
public static List<RegConfirmation> FromRegConfirmationVM(List<RegConfirmationVM> vmList)
{
List<RegConfirmation> list = new List<RegConfirmation>();
foreach (RegConfirmationVM vm in vmList)
{
RegConfirmation s = new RegConfirmation();
s.Id = vm.Id;
s.UserId = vm.UserId;
s.Device = vm.Device;
s.Code = vm.Code;
list.Add(s);
}
return list;
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/AspNetCoreWebAPI/Controllers/RoleController.cs
using Interfaces.Service;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CRUDAspNetCore5WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Consumes("application/json")]
public class RoleController : ControllerBase
{
private readonly IRoleService _roleService;
public RoleController(IRoleService roleService)
{
_roleService = roleService;
}
[HttpGet("GetRoles")]
public Object Get()
{
var data = _roleService.GetAllRoles();
var json = JsonConvert.SerializeObject(data, Formatting.Indented,
new JsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
}
);
return json;
}
}
}
<file_sep>/Project/UI/UI/wwwroot/dashboard/js/sidebar-data.js
const sidebarDoctor = [
{
id: 1,
title: "Doctor Menu One",
icon: "fas fa-calendar",
subNavs: [
{ id: 1, title: "Normal Patient", url: "./page1.html" },
{ id: 2, title: "Serious Patient", url: "./page2.html" },
{ id: 3, title: "Schedules", url: "./page2.html" },
],
},
{
id: 2,
title: "Doctor Menu Two",
icon: "fas fa-users",
subNavs: [
{ id: 1, title: "Add Patient", url: "./page3.html" },
{ id: 2, title: "Create Schedule", url: "./page4.html" },
],
},
];
const sidebarPatient = [
{
id: 1,
title: "Patient Menu One",
icon: "fas fa-calendar",
subNavs: [
{ id: 1, title: "Take Schedule", url: "./page1.html" },
{ id: 2, title: "Appointment", url: "./page2.html" },
],
},
{
id: 2,
title: "Patient Menu Two",
icon: "fas fa-users",
subNavs: [
{ id: 1, title: "Doctors Info", url: "./page3.html" },
{ id: 2, title: "Pathology Info", url: "./page4.html" },
],
},
];
<file_sep>/CRUDAspNetCore5WebAPI/Manager/Service/UserService.cs
using Manager.Converter;
using Domains;
using Interfaces.Repository;
using Interfaces.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewModels;
using Interfaces.Utility;
using BCryptNet = BCrypt.Net.BCrypt;
namespace Manager.Service
{
public class UserService: IUserService
{
private readonly IRepository<User> _user;
private readonly IUser _iUser;
private readonly IRepository<RoleEnrollment> _roleEnroll;
private readonly IRepository<Role> _role;
private IJwtUtils _jwtUtils;
private readonly IMailService _mailService;
public UserService(IRepository<User> user, IUser iUser, IRepository<RoleEnrollment> roleEnroll,
IRepository<Role> role, IJwtUtils jwtUtils, IMailService mailService)
{
_user = user;
_iUser = iUser;
_roleEnroll = roleEnroll;
_role = role;
_jwtUtils = jwtUtils;
_mailService = mailService;
}
//Get User Details By User Id
public SignUpUserVM GetUserByUserId(int userId)
{
var user = _user.GetById(userId);
//var list = new List<User>() { user };
//var userVm = UserConverter.FromUser(list);
RoleEnrollment roleEnrollment = _roleEnroll.GetAll().Where(w => w.UserId == user.Id).FirstOrDefault();
Role role = _role.GetById(roleEnrollment.RoleId);
SignUpUserVM userVM = new SignUpUserVM()
{
Id = user.Id,
Email = user.Email,
Mobile = user.Mobile,
FullName = user.FullName,
Password = <PASSWORD>,
IsEmailConfirm = user.IsEmailConfirm,
IsMobileConfirm = user.IsMobileConfirm
};
if(role != null)
{
userVM.RoleModel = new RoleVM { Id = role.Id, Title = role.Title };
}
//return userVm.FirstOrDefault();
return userVM;
}
//GET All Perso Details
public IEnumerable<SignUpUserVM> GetAllUsers()
{
try
{
var list = _user.GetAll().ToList();
var userVm = UserConverter.FromUser(list);
return userVm;
}
catch (Exception)
{
throw;
}
}
//Get User by User Name
public SignUpUserVM GetUserByEmailOrMobileAndPassword(string email, string mobile, string password)
{
SignUpUserVM signUpUserVM = new SignUpUserVM();
signUpUserVM.Result = false;
try
{
User user = _user.GetAll().Where(w => w.IsDeleted == false && (w.Email == email || w.Mobile == mobile)).FirstOrDefault();
if (user == null)
{
signUpUserVM.Message = "User not found!";
return signUpUserVM; // new AuthenticateResponse(signUpUserVM, null,);
}
var isVerified = BCryptNet.Verify(password, user.Password);
if (!isVerified)
{
signUpUserVM.Message = "Password not match!";
return signUpUserVM; // new AuthenticateResponse(null, null, "Password not match!");
}
if (!string.IsNullOrEmpty(email) && !user.IsEmailConfirm)
{
signUpUserVM.Email = email;
signUpUserVM.Message = "Email not confirmed!";
return signUpUserVM; // new AuthenticateResponse(signUpUserVM, null, message);
}
else if (!string.IsNullOrEmpty(mobile) && !user.IsMobileConfirm)
{
signUpUserVM.Mobile = mobile;
signUpUserVM.Message = "Mobile not confirmed!";
return signUpUserVM;
}
signUpUserVM.Message = "Success";
signUpUserVM.Result = true;
RoleEnrollment roleEnrollment = _roleEnroll.GetAll().Where(w => w.UserId == user.Id).FirstOrDefault();
Role role = _role.GetById(roleEnrollment.RoleId);
signUpUserVM.Id = user.Id;
signUpUserVM.Email = user.Email;
signUpUserVM.Mobile = user.Mobile;
signUpUserVM.FullName = user.FullName;
//signUpUserVM.Password = <PASSWORD>;
signUpUserVM.IsEmailConfirm = user.IsEmailConfirm;
signUpUserVM.IsMobileConfirm = user.IsMobileConfirm;
signUpUserVM.RoleModel = new RoleVM { Id = role.Id, Title = role.Title };
var jwtToken = _jwtUtils.GenerateJwtToken(signUpUserVM);
signUpUserVM.Token = jwtToken;
return signUpUserVM; // new AuthenticateResponse(userVM, jwtToken, "Success");
}
catch (Exception ex)
{
return null;
}
}
//Add User
public async Task<SignUpUserVM> AddUser(SignUpUserVM userVm)
{
userVm.Result = true;
var password = <PASSWORD>(userVm.Password);
User user = new User
{
Email = userVm.Email,
FullName = userVm.FullName,
Mobile = userVm.Mobile,
Password = <PASSWORD>
};
var existUser = _iUser.IsExists(user);
if (existUser == null)
{
var createUser = await _user.Create(user);
if (createUser != null)
{
userVm.Id = user.Id;
return userVm;
}
}
else
{
userVm.Message = "User already registered!";
userVm.Result = false;
}
userVm.Password = "";
return userVm;
}
public async Task<RegConfirmationVM> AddCode(RegConfirmationVM regConVM)
{
var vmList = new List<RegConfirmationVM>() { regConVM };
RegConfirmation regCon = RegConfirmationConverter.FromRegConfirmationVM(vmList).FirstOrDefault();
RegConfirmationVM result = new RegConfirmationVM();
List<RegConfirmation> list = new List<RegConfirmation>();
if (_iUser.IsCodeExists(regCon))
{
var updatedValue = _iUser.Update(regCon);
list = new List<RegConfirmation>() { updatedValue };
result = RegConfirmationConverter.FromRegConfirmation(list).FirstOrDefault();
return result;
}
var createdValue = await _iUser.Create(regCon);
list = new List<RegConfirmation>() { createdValue };
result = RegConfirmationConverter.FromRegConfirmation(list).FirstOrDefault();
return result;
}
public bool DeviceConfirm(RegConfirmationVM regConVM)
{
var vmList = new List<RegConfirmationVM>() { regConVM };
var regCon = RegConfirmationConverter.FromRegConfirmationVM(vmList).FirstOrDefault();
if (regCon == null) return false;
return _iUser.IsCodeExists(regCon);
}
//Delete User
public bool DeleteUser(string UserEmail)
{
try
{
var DataList = _user.GetAll().Where(x => x.Email == UserEmail).ToList();
foreach (var item in DataList)
{
_user.Delete(item);
}
return true;
}
catch (Exception ex)
{
return true;
}
}
public bool UpdateUser(SignUpUserVM userVM)
{
try
{
var vmList = new List<SignUpUserVM>() { userVM };
var user = UserConverter.FromUserVM(vmList).FirstOrDefault();
_user.Update(user);
return true;
}
catch (Exception ex)
{
return false;
}
}
public SignUpUserVM GetUserByEmailOrMobile(string emailOrMobile, bool isEmail)
{
User user;
if (isEmail)
user = _user.GetAll().Where(w => w.IsDeleted == false && w.Email == emailOrMobile).FirstOrDefault();
else
user = _user.GetAll().Where(w => w.IsDeleted == false && w.Mobile == emailOrMobile).FirstOrDefault();
SignUpUserVM userVM = new SignUpUserVM();
userVM.Id = user.Id;
userVM.Email = user.Email;
userVM.Mobile = user.Mobile;
userVM.IsEmailConfirm = user.IsEmailConfirm;
userVM.IsMobileConfirm = user.IsMobileConfirm;
return userVM;
}
}
}<file_sep>/CRUDAspNetCore5WebAPI/AspNetCoreWebAPI/Controllers/EmailController.cs
using Interfaces.Service;
using Interfaces.Utility;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ViewModels;
namespace CRUDAspNetCore5WebAPI.Controllers
{
public class EmailController : Controller
{
private readonly IMailService mailService;
public EmailController(IMailService mailService)
{
this.mailService = mailService;
}
[HttpPost("Send")]
public async Task<IActionResult> Send([FromForm] MailRequest request)
{
try
{
await mailService.SendEmailAsync(request);
return Ok();
}
catch (Exception ex)
{
throw ex;
}
}
[HttpPost("ConfirmationEmailSend")]
public async Task<IActionResult> ConfirmationEmailSend(SignUpUserVM user, string code)
{
try
{
await mailService.SendConfirmationEmailAsync(user, code);
return Ok();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Entity/ViewModels/AuthenticateResponse.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ViewModels
{
public class AuthenticateResponse
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public RoleVM Role { get; set; }
public string Token { get; set; }
public AuthenticateResponse(SignUpUserVM user, string token)
{
Id = user.Id;
FullName = user.FullName;
Email = user.Email;
Mobile = user.Mobile;
Role = user.RoleModel;
Token = token;
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Manager/Converter/RoleConverter.cs
using Domains;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewModels;
namespace Manager.Converter
{
public class RoleConverter
{
public static List<RoleVM> FromRole(List<Role> list)
{
List<RoleVM> vmList = new List<RoleVM>();
foreach (Role s in list)
{
RoleVM vm = new RoleVM();
vm.Id = s.Id;
vm.Title = s.Title;
vmList.Add(vm);
}
return vmList;
}
public static List<Role> FromRoleVM(List<RoleVM> vmList)
{
List<Role> list = new List<Role>();
foreach (RoleVM vm in vmList)
{
Role s = new Role();
s.Id = vm.Id;
s.Title = vm.Title;
list.Add(s);
}
return list;
}
}
}
<file_sep>/Readme.txt
Frist run the API
Then Run UI
home/login is the first page
home/calendar is the 2nd page
User status not completed need to cookie/storage by jquery
After login user need to get the Role then either s/he go to doctor page or patient page
patient/doctor page is the calendar page
where some event created(demo)
When patient schedule that api has created
<file_sep>/CRUDAspNetCore5WebAPI/Entity/Domains/RegConfirmation.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace Domains
{
public class RegConfirmation
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[Display(Name = "User Id")]
public int UserId { get; set; }
[Required]
[Display(Name = "Device")]
public char Device { get; set; }
[Required]
[Display(Name = "Code")]
public string Code { get; set; }
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Entity/ViewModels/SignUpUserVM.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ViewModels
{
public class SignUpUserVM
{
public SignUpUserVM()
{
RoleModel = new RoleVM();
}
public int Id { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string FullName { get; set; }
public string Password { get; set; }
public string ConfirmCode { get; set; }
public char Device { get; set; }
public bool IsEmailConfirm { get; set; }
public bool IsMobileConfirm { get; set; }
public bool IsDelete { get; set; }
public RoleVM RoleModel { get; set; }
public string Token { get; set; }
public string Message { get; set; }
public bool Result { get; set; }
public int UserRole { get; set; }//set from UI for Role
public string LoginByDevice { get; set; }
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Entity/Domains/User.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace Domains
{
[Table("Users", Schema = "dbo")]
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[Display(Name = "FullName")]
public string FullName { get; set; }
[Required]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[Display(Name = "Mobile")]
public string Mobile { get; set; }
[Required]
[Display(Name = "Created On")]
public DateTime CreatedOn { get; set; } = DateTime.Now;
[Required]
[Display(Name = "Is Deleted?")]
public bool IsDeleted { get; set; } = false;
[Required]
[Display(Name = "Is IsEmail Confirm?")]
public bool IsEmailConfirm { get; set; } = false;
[Required]
[Display(Name = "Is Mobile Confirm?")]
public bool IsMobileConfirm { get; set; } = false;
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Manager/Utility/MailService.cs
using MimeKit;
using System.IO;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using ViewModels;
using Interfaces.Utility;
using System.Text.RegularExpressions;
using System;
namespace Manager.Utility
{
public class MailService : IMailService
{
private readonly MailSettings _mailSettings;
public MailService(IOptions<MailSettings> mailSettings)
{
_mailSettings = mailSettings.Value;
}
public async Task SendEmailAsync(MailRequest mailRequest)
{
var email = new MimeMessage();
email.Sender = MailboxAddress.Parse(_mailSettings.Mail);
email.To.Add(MailboxAddress.Parse(mailRequest.ToEmail));
email.Subject = mailRequest.Subject;
var builder = new BodyBuilder();
if (mailRequest.Attachments != null)
{
byte[] fileBytes;
foreach (var file in mailRequest.Attachments)
{
if (file.Length > 0)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
fileBytes = ms.ToArray();
}
builder.Attachments.Add(file.FileName, fileBytes, ContentType.Parse(file.ContentType));
}
}
}
builder.HtmlBody = mailRequest.Body;
email.Body = builder.ToMessageBody();
using var smtp = new SmtpClient();
smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls);
smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password);
await smtp.SendAsync(email);
smtp.Disconnect(true);
}
public async Task SendConfirmationEmailAsync(SignUpUserVM request, string code)
{
string FilePath = Directory.GetCurrentDirectory() + "\\ConfirmationEmail.html";
StreamReader str = new StreamReader(FilePath);
string MailText = str.ReadToEnd();
str.Close();
MailText = MailText.Replace("[name]", request.FullName).Replace("[code]", code);
var email = new MimeMessage();
email.Sender = MailboxAddress.Parse(_mailSettings.Mail);
email.To.Add(MailboxAddress.Parse(request.Email));
email.Subject = $"Welcome {request.FullName}, Your confirmation mail.";
var builder = new BodyBuilder();
builder.HtmlBody = MailText;
email.Body = builder.ToMessageBody();
using var smtp = new SmtpClient();
smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls);
smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password);
await smtp.SendAsync(email);
smtp.Disconnect(true);
}
public bool EmailIsValid(string email)
{
try
{
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if(match.Success)
return true;
return false;
}
catch (FormatException)
{
return false;
}
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/AspNetCoreWebAPI/Controllers/AuthController.cs
using Manager.Utility;
using Interfaces.Service;
using Interfaces.Utility;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ViewModels;
using Manager.Authorization;
namespace CRUDAspNetCore5WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Consumes("application/json")]
public class AuthController : ControllerBase
{
private readonly IUserService _userService;
private readonly IRoleEnrollService _roleEnrollService;
private readonly IMailService _mailService;
public AuthController(IUserService userService, IRoleEnrollService roleEnrollService,
IMailService mailService)
{
_userService = userService;
_roleEnrollService = roleEnrollService;
_mailService = mailService;
}
[HttpPost("AddUser")]
public async Task<Object> AddUser(SignUpUserVM userVm)
{
try
{
if (userVm.UserRole == 0) return null;
var result = await _userService.AddUser(userVm);
if (result.Result)
{
userVm.Id = result.Id;
RoleEnrollmentVM roleEnroll = new RoleEnrollmentVM()
{
UserId = result.Id,
RoleId = userVm.UserRole
};
await _roleEnrollService.AddRoleEnrollment(roleEnroll);
string code = RandomService.RandomPassword();
RegConfirmationVM regCon = new RegConfirmationVM()
{
UserId = result.Id,
Device = 'E',
Code = code
};
var codeResult = await _userService.AddCode(regCon);
if (codeResult == null)
{
return false;
}
MailRequest request = new MailRequest()
{
ToEmail = result.Email,
Subject = "Your Account Confirmation Email",
Body = @"<h1>Welcome " + userVm.FullName + "!</h1> <h3> Your Confrimation Code Is " + code + "</h3> <br/><p>Thanks</p><p>My Medical HUB</p><p style='color:red;'>If your don't registed to mymedicalhub.com. Please ignore this mail!</p>"
};
await _mailService.SendEmailAsync(request);
}
var json = JsonConvert.SerializeObject(result, Formatting.Indented,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return json;
}
catch (Exception ex)
{
return null;
}
}
[HttpPost]
public Object LoginUser(SignUpUserVM user)
{
SignUpUserVM result;
if (_mailService.EmailIsValid(user.Email)) {
result = _userService.GetUserByEmailOrMobileAndPassword(user.Email, null, user.Password);
result.Device = 'E';
}
else
{
result = _userService.GetUserByEmailOrMobileAndPassword(null, user.Mobile, user.Password);
result.Device = 'M';
}
var json = JsonConvert.SerializeObject(result, Formatting.Indented,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return json;
}
[HttpPost("CheckValidation")]
public Object CheckValidation(SignUpUserVM signUpUser)
{
bool result = false;
if (string.IsNullOrEmpty(signUpUser.Email)) return null;
bool isEmail = _mailService.EmailIsValid(signUpUser.Email);
SignUpUserVM userVm = _userService.GetUserByEmailOrMobile(signUpUser.Email, isEmail);
RegConfirmationVM regCon = new RegConfirmationVM()
{
UserId = userVm.Id,
Device = signUpUser.Device,
Code = signUpUser.ConfirmCode
};
if (_userService.DeviceConfirm(regCon))
{
var user = _userService.GetUserByUserId(userVm.Id);
userVm.Email = user.Email;
userVm.Mobile = user.Mobile;
userVm.FullName = user.FullName;
userVm.Password = <PASSWORD>;
userVm.IsEmailConfirm = true;
var updateUser = _userService.UpdateUser(userVm);
if(updateUser)
{
result = true;
}
}
var json = JsonConvert.SerializeObject(result, Formatting.Indented,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return json;
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/AspNetCoreWebAPI/Controllers/ProfileController.cs
using Interfaces.Service;
using Manager.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ViewModels;
namespace AspNetCoreWebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Consumes("application/json")]
[Authorize]
public class ProfileController : ControllerBase
{
private readonly IUserService _userService;
public ProfileController(IUserService userService)
{
_userService = userService;
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/AspNetCoreWebAPI/Startup.cs
using Manager.Service;
using Manager.Utility;
using DAL.Data;
using DAL.Repository;
using Domains;
using Interfaces.Repository;
using Interfaces.Service;
using Interfaces.Utility;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using ViewModels;
using Manager.Helpers;
using Manager.Authorization;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.AspNetCore.Authentication.Cookies;
namespace CRUDAspNetCore5WebAPI
{
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
services.AddCors();
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(7);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
//services.AddControllers();
//services.AddHttpClient();
//services.AddControllers().AddJsonOptions(x =>
//{
// // serialize enums as strings in api responses (e.g. Role)
// x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
//});
// configure strongly typed settings object
services.Configure<AppSettings>(_configuration.GetSection("AppSettings"));
// configure DI for application services
services.AddScoped<IJwtUtils, JwtUtils>();
services.Configure<MailSettings>(_configuration.GetSection("MailSettings"));
services.AddTransient<IMailService, MailService>();
services.AddScoped<IRepository<User>, RepositoryUser>();
services.AddTransient<IUser, RepositoryUser>();
services.AddTransient<IRepository<Role>, RepositoryRole>();
services.AddTransient<IUserService, UserService>();
services.AddTransient<IRoleService, RoleService>();
services.AddTransient<IRoleEnrollService, RoleEnrollService>();
services.AddTransient<IRepository<RoleEnrollment>, RepositoryUserRoleEnroll>();
// services.AddCors(options =>
//{
// options.AddDefaultPolicy(
// builder =>
// {
// builder.WithOrigins("*");
// });
//});
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyMedicalhubAPI", Version = "v1" });
c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
});
//services.AddCors(c =>
//{
// c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
//});
services.AddSession();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => _configuration.Bind("JwtSettings", options))
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => _configuration.Bind("CookieSettings", options));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
//loggerFactory.AddConsole(_configuration.GetSection("Logging"));
//loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("https://localhost:44362/swagger/v1/swagger.json", "MyMedicalhubAPI v1"));
}
//else
//{
// app.UseExceptionHandler("/Home/Error");
//}
//app.UseSession();
//app.Use(async (context, next) =>
//{
// var token = context.Session.GetString("Token");
// if (!string.IsNullOrEmpty(token))
// {
// context.Request.Headers.Add("Authorization", "Bearer " + token);
// }
// await next();
//});
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseHttpsRedirection();
// global error handler
app.UseMiddleware<ErrorHandlerMiddleware>();
// custom jwt auth middleware
app.UseMiddleware<JwtMiddleware>();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession(); // use this before .UseEndpoints
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Interfaces/Service/IRoleService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewModels;
namespace Interfaces.Service
{
public interface IRoleService
{
IEnumerable<RoleVM> GetRoleById(int roleId);
IEnumerable<RoleVM> GetAllRoles();
Task<RoleVM> AddRole(RoleVM role);
bool DeleteRole(int id);
bool UpdateRole(RoleVM roleVM);
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Manager/Service/RoleEnrollService.cs
using Manager.Converter;
using Domains;
using Interfaces.Repository;
using Interfaces.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewModels;
namespace Manager.Service
{
public class RoleEnrollService: IRoleEnrollService
{
private readonly IRepository<RoleEnrollment> _enroll;
public RoleEnrollService(IRepository<RoleEnrollment> enroll)
{
_enroll = enroll;
}
//Get RoleEnrollment Details By RoleEnrollment Id
public IEnumerable<RoleEnrollmentVM> GetRoleEnrollmentByRoleEnrollmentId(int userId)
{
List<RoleEnrollment> roleEnrollments = _enroll.GetAll().Where(x => x.Id == userId).ToList();
List<RoleEnrollmentVM> roleEnrollmentVMs = RoleEnrollmentConverter.FromRoleEnrollment(roleEnrollments);
return roleEnrollmentVMs;
}
//GET All Perso Details
public IEnumerable<RoleEnrollmentVM> GetAllRoleEnrollments()
{
try
{
//var roleEnrollmentVMs = _enroll.GetAll().ToList().ConvertAll(x => (RoleEnrollmentVM)x);
List<RoleEnrollmentVM> roleEnrollmentVMs = new List<RoleEnrollmentVM>(_enroll.GetAll().ToList().Cast<RoleEnrollmentVM>());
return roleEnrollmentVMs;
}
catch (Exception)
{
throw;
}
}
public async Task<RoleEnrollmentVM> AddRoleEnrollment(RoleEnrollmentVM roleEnrollmentVM)
{
var vmList = new List<RoleEnrollmentVM>() { roleEnrollmentVM };
var roleEnrollment = RoleEnrollmentConverter.FromRoleEnrollmentVM(vmList).FirstOrDefault();
var resultRoleEnrollment = await _enroll.Create(roleEnrollment);
var list = new List<RoleEnrollment>() { resultRoleEnrollment };
var vm = RoleEnrollmentConverter.FromRoleEnrollment(list).FirstOrDefault();
return vm;
}
//Delete RoleEnrollment
public bool DeleteRoleEnrollment(int id)
{
try
{
var DataList = _enroll.GetAll().Where(x => x.Id == id).ToList();
foreach (var item in DataList)
{
_enroll.Delete(item);
}
return true;
}
catch (Exception)
{
return true;
}
}
//Update RoleEnrollment Details
public bool UpdateRoleEnrollment(RoleEnrollmentVM roleEnrollmentVM)
{
try
{
var vmList = new List<RoleEnrollmentVM>() { roleEnrollmentVM };
var roleEnrollment = RoleEnrollmentConverter.FromRoleEnrollmentVM(vmList).FirstOrDefault();
_enroll.Update(roleEnrollment);
return true;
}
catch (Exception)
{
return true;
}
}
}
}<file_sep>/CRUDAspNetCore5WebAPI/Interfaces/Utility/IJwtUtils.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewModels;
namespace Interfaces.Utility
{
public interface IJwtUtils
{
public string GenerateJwtToken(SignUpUserVM user);
public int? ValidateJwtToken(string token);
}
}
<file_sep>/CRUDAspNetCore5WebAPI/Manager/Service/RoleService.cs
using Manager.Converter;
using Domains;
using Interfaces.Repository;
using Interfaces.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ViewModels;
namespace Manager.Service
{
public class RoleService: IRoleService
{
private readonly IRepository<Role> _role;
public RoleService(IRepository<Role> role)
{
_role = role;
}
public IEnumerable<RoleVM> GetRoleById(int roleId)
{
var roles = _role.GetAll().Where(x => x.Id == roleId).ToList();
var roleVMs = RoleConverter.FromRole(roles);
return roleVMs;
}
//GET All Perso Details
public IEnumerable<RoleVM> GetAllRoles()
{
try
{
var roles = _role.GetAll().ToList();
var roleVMs = RoleConverter.FromRole(roles);
return roleVMs;
}
catch (Exception)
{
throw;
}
}
public async Task<RoleVM> AddRole(RoleVM roleVM)
{
var vmList = new List<RoleVM>() { roleVM };
var role = RoleConverter.FromRoleVM(vmList).FirstOrDefault();
var resultRole = await _role.Create(role);
var resultRoleList = new List<Role>() { resultRole };
var resultVM = RoleConverter.FromRole(resultRoleList).FirstOrDefault();
return resultVM;
}
//Delete Role
public bool DeleteRole(int id)
{
try
{
var DataList = _role.GetAll().Where(x => x.Id == id).ToList();
foreach (var item in DataList)
{
_role.Delete(item);
}
return true;
}
catch (Exception)
{
return true;
}
}
public bool UpdateRole(RoleVM roleVM)
{
try
{
var vmList = new List<RoleVM>() { roleVM };
var role = RoleConverter.FromRoleVM(vmList).FirstOrDefault();
_role.Update(role);
return true;
}
catch (Exception)
{
return true;
}
}
}
}<file_sep>/CRUDAspNetCore5WebAPI/AspNetCoreWebAPI/Controllers/PatientController.cs
using Manager.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AspNetCoreWebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Consumes("application/json")]
[Authorize(roles: "Patient")]
public class PatientController : ControllerBase
{
[HttpGet]
public Object Get()
{
List<string> patient = new List<string>()
{
"Bilkis",
"<NAME>",
"<NAME>"
};
var json = JsonConvert.SerializeObject(patient, Formatting.Indented,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return json;
}
}
}
|
39310846f723831d91b7c7389f207f645268326e
|
[
"JavaScript",
"C#",
"Text"
] | 44
|
C#
|
asalam345/mymedicalhub
|
31c3fac2966ef59a67e4f8cd205181d14b1066f8
|
e35410c4b244c62825563d853ab24f5d1d9c5fa2
|
refs/heads/webarcore_57.0.2987.5
|
<file_sep>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/vr/android/tango/tango_vr_device.h"
#include "tango_support.h"
#include "base/trace_event/trace_event.h"
#include "TangoHandler.h"
#define THIS_VALUE_NEEDS_TO_BE_OBTAINED_FROM_THE_TANGO_API -1
using base::android::AttachCurrentThread;
using tango_chromium::TangoHandler;
using tango_chromium::Hit;
const float RAD_2_DEG = 180.0 / M_PI;
namespace device {
TangoVRDevice::TangoVRDevice(TangoVRDeviceProvider* provider)
: tangoVRDeviceProvider(provider) {
tangoCoordinateFramePair.base = TANGO_COORDINATE_FRAME_START_OF_SERVICE;
tangoCoordinateFramePair.target = TANGO_COORDINATE_FRAME_DEVICE;
}
TangoVRDevice::~TangoVRDevice() {
}
mojom::VRDisplayInfoPtr TangoVRDevice::GetVRDevice() {
TRACE_EVENT0("input", "TangoVRDevice::GetVRDevice");
mojom::VRDisplayInfoPtr device = mojom::VRDisplayInfo::New();
device->displayName = "Tango VR Device";
device->capabilities = mojom::VRDisplayCapabilities::New();
device->capabilities->hasOrientation = true;
device->capabilities->hasPosition = true;
device->capabilities->hasExternalDisplay = false;
device->capabilities->canPresent = false;
device->capabilities->hasPassThroughCamera = true;
device->leftEye = mojom::VREyeParameters::New();
device->rightEye = mojom::VREyeParameters::New();
mojom::VREyeParametersPtr& left_eye = device->leftEye;
mojom::VREyeParametersPtr& right_eye = device->rightEye;
left_eye->fieldOfView = mojom::VRFieldOfView::New();
right_eye->fieldOfView = mojom::VRFieldOfView::New();
left_eye->offset.resize(3);
right_eye->offset.resize(3);
TangoHandler* tangoHandler = TangoHandler::getInstance();
if (!tangoHandler->isConnected()) {
// We may not be able to get an instance of TangoHandler right away, so
// stub in some data till we have one.
left_eye->fieldOfView->upDegrees = 45;
left_eye->fieldOfView->downDegrees = 45;
left_eye->fieldOfView->leftDegrees = 45;
left_eye->fieldOfView->rightDegrees = 45;
right_eye->fieldOfView->upDegrees = 45;
right_eye->fieldOfView->downDegrees = 45;
right_eye->fieldOfView->leftDegrees = 45;
right_eye->fieldOfView->rightDegrees = 45;
left_eye->offset[0] = -0.0;
left_eye->offset[1] = -0.0;
left_eye->offset[2] = -0.0;
right_eye->offset[0] = 0.0;
right_eye->offset[1] = 0.0;
right_eye->offset[2] = 0.0;
left_eye->renderWidth = THIS_VALUE_NEEDS_TO_BE_OBTAINED_FROM_THE_TANGO_API/*screen_size[0]*/ / 2.0;
left_eye->renderHeight = THIS_VALUE_NEEDS_TO_BE_OBTAINED_FROM_THE_TANGO_API/*screen_size[1]*/;
right_eye->renderWidth = THIS_VALUE_NEEDS_TO_BE_OBTAINED_FROM_THE_TANGO_API/*screen_size[0]*/ / 2.0;
right_eye->renderHeight = THIS_VALUE_NEEDS_TO_BE_OBTAINED_FROM_THE_TANGO_API/*screen_size[1]*/;
return device;
}
uint32_t iw = THIS_VALUE_NEEDS_TO_BE_OBTAINED_FROM_THE_TANGO_API;
uint32_t ih = THIS_VALUE_NEEDS_TO_BE_OBTAINED_FROM_THE_TANGO_API;
double fx = THIS_VALUE_NEEDS_TO_BE_OBTAINED_FROM_THE_TANGO_API;
double fy = THIS_VALUE_NEEDS_TO_BE_OBTAINED_FROM_THE_TANGO_API;
double cx = THIS_VALUE_NEEDS_TO_BE_OBTAINED_FROM_THE_TANGO_API;
double cy = THIS_VALUE_NEEDS_TO_BE_OBTAINED_FROM_THE_TANGO_API;
tangoHandler->getCameraImageSize(&iw, &ih);
tangoHandler->getCameraFocalLength(&fx, &fy);
tangoHandler->getCameraPoint(&cx, &cy);
float vDegrees = atan(ih / (2.0 * fy)) * RAD_2_DEG;
float hDegrees = atan(iw / (2.0 * fx)) * RAD_2_DEG;
left_eye->fieldOfView->upDegrees = vDegrees;
left_eye->fieldOfView->downDegrees = vDegrees;
left_eye->fieldOfView->leftDegrees = hDegrees;
left_eye->fieldOfView->rightDegrees = hDegrees;
right_eye->fieldOfView->upDegrees = vDegrees;
right_eye->fieldOfView->downDegrees = vDegrees;
right_eye->fieldOfView->leftDegrees = hDegrees;
right_eye->fieldOfView->rightDegrees = hDegrees;
left_eye->offset[0] = 0.0f;
left_eye->offset[1] = 0.0f;
left_eye->offset[2] = 0.0f;
right_eye->offset[0] = 0.0f;
right_eye->offset[1] = 0.0f;
right_eye->offset[2] = 0.0f;
left_eye->renderWidth = iw;
left_eye->renderHeight = ih;
right_eye->renderWidth = iw;
right_eye->renderHeight = ih;
// Store the orientation values so we can check in future GetPose()
// calls if we need to update camera intrinsics and regenerate the
// VRDeviceInfoPtr
lastSensorOrientation = tangoHandler->getSensorOrientation();
lastActivityOrientation = tangoHandler->getActivityOrientation();
return device;
}
mojom::VRPosePtr TangoVRDevice::GetPose() {
// Check to see if orientation has changed, and if so, fire
// an OnChanged() so that the VRFieldOfView can be updated,
// with the up-to-date VRDeviceInfoPtr sent to WebKit for correct
// projection matrix calculations.
TangoHandler* tangoHandler = TangoHandler::getInstance();
if (tangoHandler->isConnected() &&
(lastSensorOrientation != tangoHandler->getSensorOrientation() ||
lastActivityOrientation != tangoHandler->getActivityOrientation())) {
VRDevice::OnChanged();
}
TangoPoseData tangoPoseData;
mojom::VRPosePtr pose = nullptr;
if (tangoHandler->isConnected() && tangoHandler->getPose(&tangoPoseData))
{
pose = mojom::VRPose::New();
pose->timestamp = base::Time::Now().ToJsTime();
pose->orientation.emplace(4);
pose->position.emplace(3);
pose->orientation.value()[0] = tangoPoseData.orientation[0]/*decomposed_transform.quaternion[0]*/;
pose->orientation.value()[1] = tangoPoseData.orientation[1]/*decomposed_transform.quaternion[1]*/;
pose->orientation.value()[2] = tangoPoseData.orientation[2]/*decomposed_transform.quaternion[2]*/;
pose->orientation.value()[3] = tangoPoseData.orientation[3]/*decomposed_transform.quaternion[3]*/;
pose->position.value()[0] = tangoPoseData.translation[0]/*decomposed_transform.translate[0]*/;
pose->position.value()[1] = tangoPoseData.translation[1]/*decomposed_transform.translate[1]*/;
pose->position.value()[2] = tangoPoseData.translation[2]/*decomposed_transform.translate[2]*/;
}
return pose;
}
void TangoVRDevice::ResetPose() {
TangoHandler::getInstance()->resetPose();
}
mojom::VRPassThroughCameraPtr TangoVRDevice::GetPassThroughCamera()
{
TangoHandler* tangoHandler = TangoHandler::getInstance();
mojom::VRPassThroughCameraPtr seeThroughCameraPtr = nullptr;
if (tangoHandler->isConnected())
{
seeThroughCameraPtr = mojom::VRPassThroughCamera::New();
tangoHandler->getCameraImageSize(&(seeThroughCameraPtr->width), &(seeThroughCameraPtr->height));
tangoHandler->getCameraImageTextureSize(&(seeThroughCameraPtr->textureWidth), &(seeThroughCameraPtr->textureHeight));
tangoHandler->getCameraFocalLength(&(seeThroughCameraPtr->focalLengthX), &(seeThroughCameraPtr->focalLengthY));
tangoHandler->getCameraPoint(&(seeThroughCameraPtr->pointX), &(seeThroughCameraPtr->pointY));
seeThroughCameraPtr->orientation = tangoHandler->getSensorOrientation();
}
return seeThroughCameraPtr;
}
std::vector<mojom::VRHitPtr> TangoVRDevice::HitTest(float x, float y)
{
std::vector<mojom::VRHitPtr> mojomHits;
if (TangoHandler::getInstance()->isConnected())
{
std::vector<Hit> hits;
if (TangoHandler::getInstance()->hitTest(x, y, hits) && hits.size() > 0)
{
std::vector<Hit>::size_type size = hits.size();
mojomHits.resize(size);
for (std::vector<Hit>::size_type i = 0; i < size; i++)
{
mojomHits[i] = mojom::VRHit::New();
mojomHits[i]->modelMatrix.resize(16);
for (int j = 0; j < 16; j++)
{
mojomHits[i]->modelMatrix[j] = hits[i].modelMatrix[j];
}
}
}
}
return mojomHits;
}
void TangoVRDevice::RequestPresent(const base::Callback<void(bool)>& callback) {
// gvr_provider_->RequestPresent(callback);
}
void TangoVRDevice::SetSecureOrigin(bool secure_origin) {
// secure_origin_ = secure_origin;
// if (delegate_)
// delegate_->SetWebVRSecureOrigin(secure_origin_);
}
void TangoVRDevice::ExitPresent() {
// gvr_provider_->ExitPresent();
// OnExitPresent();
}
void TangoVRDevice::SubmitFrame(mojom::VRPosePtr pose) {
// if (delegate_)
// delegate_->SubmitWebVRFrame();
}
void TangoVRDevice::UpdateLayerBounds(mojom::VRLayerBoundsPtr left_bounds,
mojom::VRLayerBoundsPtr right_bounds) {
// if (!delegate_)
// return;
// gvr::Rectf left_gvr_bounds;
// left_gvr_bounds.left = left_bounds->left;
// left_gvr_bounds.top = 1.0f - left_bounds->top;
// left_gvr_bounds.right = left_bounds->left + left_bounds->width;
// left_gvr_bounds.bottom = 1.0f - (left_bounds->top + left_bounds->height);
// gvr::Rectf right_gvr_bounds;
// right_gvr_bounds.left = right_bounds->left;
// right_gvr_bounds.top = 1.0f - right_bounds->top;
// right_gvr_bounds.right = right_bounds->left + right_bounds->width;
// right_gvr_bounds.bottom = 1.0f - (right_bounds->top + right_bounds->height);
// delegate_->UpdateWebVRTextureBounds(left_gvr_bounds, right_gvr_bounds);
}
} // namespace device
<file_sep>/*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cstdlib>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl3.h>
#include <cassert>
#include <cmath>
#include "TangoHandler.h"
#include <sstream>
#include <thread>
#include "glm.hpp"
#include "gtc/type_ptr.hpp"
#include "gtx/transform.hpp"
#include "gtx/quaternion.hpp"
using namespace glm;
namespace {
const int kVersionStringLength = 128;
// The minimum Tango Core version required from this application.
const int kTangoCoreMinimumVersion = 9377;
const float ANDROID_WEBVIEW_ADDRESS_BAR_HEIGHT = 125;
void onTextureAvailable(void* context, TangoCameraId tangoCameraId)
{
// Do nothing for now.
}
void onTangoEventAvailable(void* context, const TangoEvent* event) {
tango_chromium::TangoHandler* tangoHandler =
static_cast<tango_chromium::TangoHandler*>(context);
tangoHandler->onTangoEventAvailable(event);
}
void matrixFrustum(float const & left,
float const & right,
float const & bottom,
float const & top,
float const & near,
float const & far,
float* matrix)
{
float x = 2 * near / ( right - left );
float y = 2 * near / ( top - bottom );
float a = ( right + left ) / ( right - left );
float b = ( top + bottom ) / ( top - bottom );
float c = - ( far + near ) / ( far - near );
float d = - 2 * far * near / ( far - near );
matrix[ 0 ] = x; matrix[ 4 ] = 0; matrix[ 8 ] = a; matrix[ 12 ] = 0;
matrix[ 1 ] = 0; matrix[ 5 ] = y; matrix[ 9 ] = b; matrix[ 13 ] = 0;
matrix[ 2 ] = 0; matrix[ 6 ] = 0; matrix[ 10 ] = c; matrix[ 14 ] = d;
matrix[ 3 ] = 0; matrix[ 7 ] = 0; matrix[ 11 ] = - 1; matrix[ 15 ] = 0;
// matrix[0] = (float(2) * near) / (right - left);
// matrix[5] = (float(2) * near) / (top - bottom);
// matrix[2][0] = (right + left) / (right - left);
// matrix[2][1] = (top + bottom) / (top - bottom);
// matrix[10] = -(farVal + nearVal) / (farVal - nearVal);
// matrix[2][3] = float(-1);
// matrix[3][2] = -(float(2) * farVal * nearVal) / (farVal - nearVal);
}
void matrixProjection(float width, float height,
float fx, float fy,
float cx, float cy,
float near, float far,
float* matrix)
{
const float xscale = near / fx;
const float yscale = near / fy;
const float xoffset = (cx - (width / 2.0)) * xscale;
// Color camera's coordinates has y pointing downwards so we negate this term.
const float yoffset = -(cy - (height / 2.0)) * yscale;
matrixFrustum(xscale * -width / 2.0f - xoffset,
xscale * width / 2.0f - xoffset,
yscale * -height / 2.0f - yoffset,
yscale * height / 2.0f - yoffset, near, far,
matrix);
}
mat4 SS_T_GL;
mat4 SS_T_GL_INV;
mat4 mat4FromTranslationOrientation(double *translation, double *orientation) {
vec3 translationV3 = vec3((float)translation[0],
(float)translation[1], (float)translation[2]);
quat orientationQ = quat((float)orientation[0], (float)orientation[1],
(float)orientation[2], (float)orientation[3]);
mat4 m = mat4();
float* out;
out = value_ptr(m);
float x = (float)orientation[0];
float y = (float)orientation[1];
float z = (float)orientation[2];
float w = (float)orientation[3];
float x2 = x + x;
float y2 = y + y;
float z2 = z + z;
float xx = x * x2;
float xy = x * y2;
float xz = x * z2;
float yy = y * y2;
float yz = y * z2;
float zz = z * z2;
float wx = w * x2;
float wy = w * y2;
float wz = w * z2;
out[0] = 1 - (yy + zz);
out[1] = xy + wz;
out[2] = xz - wy;
out[3] = 0;
out[4] = xy - wz;
out[5] = 1 - (xx + zz);
out[6] = yz + wx;
out[7] = 0;
out[8] = xz + wy;
out[9] = yz - wx;
out[10] = 1 - (xx + yy);
out[11] = 0;
out[12] = (float)translation[0];
out[13] = (float)translation[1];
out[14] = (float)translation[2];
out[15] = 1;
return m;
};
float rayIntersectsPlane(const vec3 &planeNormal, const vec3 &planePosition,
const vec3 &rayOrigin, const vec3 &rayDirection) {
float denom = glm::dot(planeNormal, rayDirection);
vec3 rayToPlane = planePosition - rayOrigin;
return glm::dot(rayToPlane, planeNormal) / denom;
}
vec3 transformVec3ByMat4(const vec3 &v, const mat4 &m4) {
const float* m;
m = value_ptr(m4);
float x = v[0];
float y = v[1];
float z = v[2];
float w = m[3] * x + m[7] * y + m[11] * z + m[15];
if (w == 0) {
w = 1.0f;
}
return vec3(
(m[0] * x + m[4] * y + m[8] * z + m[12]) / w,
(m[1] * x + m[5] * y + m[9] * z + m[13]) / w,
(m[2] * x + m[6] * y + m[10] * z + m[14]) / w);
}
void setFloat16FromMat4(float *out, const mat4 &m4) {
const float* fM = value_ptr(m4);
for (int i = 0; i < 16; i++) {
out[i] = fM[i];
}
}
bool isPointInPolygon(const vec3 &point, const vec3* polygonPoints, int count) {
if (count < 3)
{
return false;
}
LOGE("POINT: (%f, %f, %f)", point.x, point.y, point.z);
LOGE("POLY");
vec3 lastUp = vec3(0, 0, 0);
for (int i = 0; i < count; ++i)
{
LOGE("(%f, %f, %f", polygonPoints[i].x, polygonPoints[i].y, polygonPoints[i].z);
vec3 v0 = point - polygonPoints[i];
vec3 v1;
if (i == count - 1)
{
v1 = polygonPoints[0] - polygonPoints[i];
}
else
{
v1 = polygonPoints[i + 1] - polygonPoints[i];
}
vec3 up = glm::cross(v0, v1);
if (i != 0)
{
float sign = glm::dot(up, lastUp);
if (sign < 0)
{
return false;
}
}
lastUp = up;
}
LOGE("/POLY");
return true;
}
} // End anonymous namespace
namespace tango_chromium {
TangoHandler* TangoHandler::instance = 0;
TangoHandler* TangoHandler::getInstance()
{
if (instance == 0)
{
instance = new TangoHandler();
}
return instance;
}
void TangoHandler::releaseInstance()
{
delete instance;
instance = 0;
}
TangoHandler::TangoHandler(): connected(false)
, tangoConfig(nullptr)
, lastTangoImageBufferTimestamp(0)
, cameraImageWidth(0)
, cameraImageHeight(0)
, cameraImageTextureWidth(0)
, cameraImageTextureHeight(0)
, textureIdConnected(false)
{
// SS means Start of Service: this matrix does the conversion from Start of Service transform
// to OpenGL (tango-space has z as the up-vector, not y).
float ss_t_gl[16] = {1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1};
SS_T_GL = make_mat4(ss_t_gl);
SS_T_GL_INV = inverse(SS_T_GL);
}
TangoHandler::~TangoHandler()
{
TangoConfig_free(tangoConfig);
tangoConfig = nullptr;
}
void TangoHandler::onCreate(JNIEnv* env, jobject activity, int activityOrientation, int sensorOrientation)
{
this->activityOrientation = activityOrientation;
this->sensorOrientation = sensorOrientation;
}
void TangoHandler::onTangoServiceConnected(JNIEnv* env, jobject tango)
{
TangoService_CacheTangoObject(env, tango);
connect();
}
void TangoHandler::connect()
{
TangoErrorType result;
// TANGO_CONFIG_DEFAULT is enabling Motion Tracking and disabling Depth
// Perception.
tangoConfig = TangoService_getConfig(TANGO_CONFIG_DEFAULT);
if (tangoConfig == nullptr)
{
LOGE("TangoHandler::connect, TangoService_getConfig error.");
std::exit (EXIT_SUCCESS);
}
// Set auto-recovery for motion tracking as requested by the user.
result = TangoConfig_setBool(tangoConfig, "config_enable_auto_recovery", true);
if (result != TANGO_SUCCESS) {
LOGE("TangoHandler::connect, config_enable_auto_recovery activation failed with error code: %d", result);
std::exit(EXIT_SUCCESS);
}
// Enable color camera from config.
result = TangoConfig_setBool(tangoConfig, "config_enable_color_camera", true);
if (result != TANGO_SUCCESS) {
LOGE("TangoHandler::connect, config_enable_color_camera() failed with error code: %d", result);
std::exit(EXIT_SUCCESS);
}
// Note that it is super important for AR applications that we enable low
// latency IMU integration so that we have pose information available as
// quickly as possible. Without setting this flag, you will often receive
// invalid poses when calling getPoseAtTime() for an image.
result = TangoConfig_setBool(tangoConfig, "config_enable_low_latency_imu_integration", true);
if (result != TANGO_SUCCESS) {
LOGE("TangoHandler::connect, failed to enable low latency imu integration.");
std::exit(EXIT_SUCCESS);
}
// Drift correction allows motion tracking to recover after it loses tracking.
// The drift corrected pose is is available through the frame pair with
// base frame AREA_DESCRIPTION and target frame DEVICE.
result = TangoConfig_setBool(tangoConfig, "config_enable_drift_correction", true);
if (result != TANGO_SUCCESS) {
LOGE("TangoHandler::connect, enabling config_enable_drift_correction "
"failed with error code: %d", result);
std::exit(EXIT_SUCCESS);
}
// Enable Depth Perception.
result = TangoConfig_setBool(tangoConfig, "config_enable_depth", true);
if (result != TANGO_SUCCESS)
{
LOGE("TangoHandler::connect, config_enable_depth activation failed with error code: %d.", result);
std::exit(EXIT_SUCCESS);
}
// Enabling experimental plane finding.
result = TangoConfig_setBool(tangoConfig,
"config_experimental_enable_plane_detection", true);
if (result != TANGO_SUCCESS) {
LOGE("TangoHandler::connect, failed to enable experimental plane finding.");
std::exit(EXIT_SUCCESS);
}
result = TangoConfig_setInt32(tangoConfig, "config_depth_mode",
TANGO_POINTCLOUD_XYZC);
if (result != TANGO_SUCCESS) {
LOGE(
"TangoHandler::connect, failed to configure point cloud to "
"XYZC.");
std::exit(EXIT_SUCCESS);
}
// Get TangoCore version string from service.
char tangoCoreVersionCharArray[kVersionStringLength];
result = TangoConfig_getString(tangoConfig, "tango_service_library_version",
tangoCoreVersionCharArray, kVersionStringLength);
if (result != TANGO_SUCCESS) {
LOGE(
"TangoHandler::connect, get tango core version failed with error"
"code: %d",
result);
std::exit(EXIT_SUCCESS);
}
tangoCoreVersionString = tangoCoreVersionCharArray;
// Connect some callbacks
result = TangoService_connectOnTextureAvailable(TANGO_CAMERA_COLOR, this, ::onTextureAvailable);
if (result != TANGO_SUCCESS)
{
LOGE("TangoHandler::connect, failed to connect texture callback with error code: %d", result);
std::exit(EXIT_SUCCESS);
}
// Attach onEventAvailable callback.
// The callback will be called after the service is connected.
result = TangoService_connectOnTangoEvent(::onTangoEventAvailable);
if (result != TANGO_SUCCESS) {
LOGE(
"TangoHandler::connect, failed to connect to event callback with error"
"code: %d",
result);
std::exit(EXIT_SUCCESS);
}
// Connect the tango service.
if (TangoService_connect(this, tangoConfig) != TANGO_SUCCESS)
{
LOGE("TangoHandler::connect, TangoService_connect error.");
std::exit (EXIT_SUCCESS);
}
// Get the intrinsics for the color camera and pass them on to the depth
// image.
result = TangoService_getCameraIntrinsics(TANGO_CAMERA_COLOR, &tangoCameraIntrinsics);
if (result != TANGO_SUCCESS) {
LOGE("TangoHandler::connect: Failed to get the intrinsics for the color camera.");
std::exit(EXIT_SUCCESS);
}
// Initialize TangoSupport context.
TangoSupport_initialize(TangoService_getPoseAtTime,
TangoService_getCameraIntrinsics);
connected = true;
// Update camera intrinsics after connection which will take into account
// device rotation
this->updateCameraIntrinsics();
}
void TangoHandler::disconnect()
{
TangoService_disconnect();
cameraImageWidth = cameraImageHeight =
cameraImageTextureWidth = cameraImageTextureHeight = 0;
textureIdConnected = false;
connected = false;
}
void TangoHandler::onPause()
{
disconnect();
}
void TangoHandler::onDeviceRotationChanged(int activityOrientation, int sensorOrientation)
{
LOGE("TangoHandler::onDeviceRotationChanged; activityOrientation=%d, sensorOrientation=%d",
activityOrientation, sensorOrientation);
this->activityOrientation = activityOrientation;
this->sensorOrientation = sensorOrientation;
this->updateCameraIntrinsics();
}
void TangoHandler::onTangoEventAvailable(const TangoEvent* event)
{
}
bool TangoHandler::isConnected() const
{
return connected;
}
bool TangoHandler::getPose(TangoPoseData* tangoPoseData)
{
bool result = connected;
if (connected)
{
double timestamp = hasLastTangoImageBufferTimestampChangedLately() ? lastTangoImageBufferTimestamp : 0.0;
// LOGI("JUDAX: TangoHandler::getPose timestamp = %lf", timestamp);
// For reference purpose: ADF to start of service request parameters.
// {TANGO_COORDINATE_FRAME_AREA_DESCRIPTION,
// TANGO_COORDINATE_FRAME_DEVICE}
// then fallback to:
// {TANGO_COORDINATE_FRAME_START_OF_SERVICE,
// TANGO_COORDINATE_FRAME_DEVICE}
result = TangoSupport_getPoseAtTime(
timestamp, TANGO_COORDINATE_FRAME_START_OF_SERVICE,
TANGO_COORDINATE_FRAME_CAMERA_COLOR, TANGO_SUPPORT_ENGINE_OPENGL,
TANGO_SUPPORT_ENGINE_OPENGL,
static_cast<TangoSupport_Rotation>(activityOrientation), tangoPoseData) == TANGO_SUCCESS;
if (!result)
{
LOGE("TangoHandler::getPose: Failed to get the pose.");
}
}
return result;
}
bool TangoHandler::getProjectionMatrix(float near, float far, float* projectionMatrix)
{
if (!connected) return false;
bool result = this->updateCameraIntrinsics();
if (!result) {
LOGE(
"TangoHandler::getProjectionMatrix, failed to get camera intrinsics");
return false;
}
float image_width = static_cast<float>(tangoCameraIntrinsics.width);
float image_height = static_cast<float>(tangoCameraIntrinsics.height);
float fx = static_cast<float>(tangoCameraIntrinsics.fx);
float fy = static_cast<float>(tangoCameraIntrinsics.fy);
float cx = static_cast<float>(tangoCameraIntrinsics.cx);
float cy = static_cast<float>(tangoCameraIntrinsics.cy);
matrixProjection(
image_width, image_height, fx, fy, cx, cy, near,
far, projectionMatrix);
return true;
}
bool TangoHandler::hitTest(float x, float y, std::vector<Hit>& hits)
{
bool result = false;
if (connected)
{
TangoPlaneData* planes = 0;
size_t numberOfPlanes = 0;
if (TangoService_Experimental_getPlanes(&planes, &numberOfPlanes) == TANGO_SUCCESS)
{
if (numberOfPlanes == 0) {
return result;
}
// Set the projection matrix.
float* fM;
mat4 projectionMatrix;
fM = value_ptr(projectionMatrix);
// TODO(lincolnfrog): near and far values should not be constants. Use the values
// supplied by the client.
getProjectionMatrix(0.01, 10000, fM);
// Set the model view matrix.
TangoPoseData poseData;
getPose(&poseData);
mat4 viewMatrix = mat4FromTranslationOrientation(
poseData.translation, poseData.orientation);
viewMatrix = inverse(viewMatrix);
// Combine the projection and model view matrices.
mat4 projViewMatrix = projectionMatrix * viewMatrix;
// Invert the combined matrix because we need to go from screen -> world.
projViewMatrix = inverse(projViewMatrix);
// Create a ray in screen-space for the hit test ([-1, 1] with y flip).
vec3 rayStart = vec3((2 * x) - 1, (2 * (1 - y)) - 1, 0);
vec3 rayEnd = vec3((2 * x) - 1, (2 * (1 - y)) - 1, 1);
// Transform the ray into world-space.
vec3 worldRayOrigin = transformVec3ByMat4(rayStart, projViewMatrix);
vec3 worldRayDirection = transformVec3ByMat4(rayEnd, projViewMatrix);
worldRayDirection -= worldRayOrigin;
worldRayDirection = normalize(worldRayDirection);
// Check each plane for intersections.
for (int i = 0; i < numberOfPlanes; i++) {
TangoPlaneData planeData = planes[i];
if (!planeData.is_valid) {
// This plane is no longer valid, so skip it.
continue;
}
if (planeData.subsumed_by != -1) {
// This plane has been subsumed by another plane, so skip it.
continue;
}
TangoPoseData planePose = planeData.pose;
// Get the plane transform matrix.
mat4 planeMatrix = mat4FromTranslationOrientation(
planePose.translation, planePose.orientation);
// Plane is in the tango coordinates, so transform into GL coordinate space.
planeMatrix = SS_T_GL_INV * planeMatrix * SS_T_GL;
// Get the plane center in world-space.
vec3 planeCenter = vec3(planeData.center_x, 0, planeData.center_y);
vec3 planePosition = transformVec3ByMat4(planeCenter, planeMatrix);
// Assume all planes are oriented horizontally.
vec3 planeNormal = vec3(0, 1, 0);
// Check if the ray intersects the plane.
float t = rayIntersectsPlane(planeNormal, planePosition, worldRayOrigin, worldRayDirection);
// If t < 0, there is no intersection.
if (t < 0) {
continue;
}
// Calculate the intersection point.
vec3 planeIntersection = worldRayOrigin + (worldRayDirection * t);
// Convert the intersection into plane-space.
mat4 planeMatrixInv = inverse(planeMatrix);
vec3 planeIntersectionLocal = transformVec3ByMat4(planeIntersection, planeMatrixInv);
// Check if the intersection is outside of the extent of the plane.
if (abs(planeIntersectionLocal.x - planeData.center_x) > planeData.width) {
continue;
}
if (abs(planeIntersectionLocal.y - planeData.center_y) > planeData.height) {
continue;
}
/*
// TODO(lincolnfrog): enable polygon test when we figure out why the polygon is so bad.s
// Transform all the points into world space using the plane matrix.
vec3 polygonPoints[planeData.boundary_point_num];
for (int i = 0; i < planeData.boundary_point_num; ++i) {
polygonPoints[i] = transformVec3ByMat4(
vec3((float)planeData.boundary_polygon[i * 2], 0, (float)planeData.boundary_polygon[(i * 2) + 1]),
planeMatrix);
}
if(!isPointInPolygon(planeIntersection, polygonPoints, planeData.boundary_point_num)) {
LOGE("%i Rejected (POLY)", planeData.id);
continue;
}
*/
mat4 hitMatrix = translate(mat4(1.0f), planeIntersection);
Hit hit;
setFloat16FromMat4(hit.modelMatrix, hitMatrix);
hits.push_back(hit);
}
// Sort the hits based on distance to the camera.
auto sortFunc = [worldRayOrigin] (Hit a, Hit b) {
vec3 vA = vec3(a.modelMatrix[12], a.modelMatrix[13], a.modelMatrix[14]);
float dA = glm::length2(vA - worldRayOrigin);
vec3 vB = vec3(b.modelMatrix[12], b.modelMatrix[13], b.modelMatrix[14]);
float dB = glm::length2(vB - worldRayOrigin);
return dA < dB;
};
std::sort(hits.begin(), hits.end(), sortFunc);
TangoPlaneData_free(planes, numberOfPlanes);
}
result = hits.size() > 0;
}
return result;
}
void TangoHandler::resetPose()
{
TangoService_resetMotionTracking();
}
bool TangoHandler::updateCameraIntrinsics()
{
if (!connected) {
LOGE("TangoHandler::updateCameraIntrinsics, is not connected.");
return false;
}
int result = TangoSupport_getCameraIntrinsicsBasedOnDisplayRotation(
TANGO_CAMERA_COLOR, static_cast<TangoSupport_Rotation>(activityOrientation),
&tangoCameraIntrinsics);
if (result != TANGO_SUCCESS) {
LOGE(
"TangoHandler::updateCameraIntrinsics, failed to get camera intrinsics "
"with error code: %d",
result);
return false;
}
/*
LOGE("TangoHandler::updateCameraIntrinsics, success. fx: %f, fy: %f, width: %d, height: %d, cx: %f, cy: %f",
tangoCameraIntrinsics.fx,
tangoCameraIntrinsics.fy,
tangoCameraIntrinsics.width,
tangoCameraIntrinsics.height,
tangoCameraIntrinsics.cx,
tangoCameraIntrinsics.cy);
*/
// Always subtract the height of the address bar since we cannot
// get rid of it
tangoCameraIntrinsics.height -= ANDROID_WEBVIEW_ADDRESS_BAR_HEIGHT;
// Update the stored values for width and height
cameraImageWidth = cameraImageTextureWidth = tangoCameraIntrinsics.width;
cameraImageHeight = cameraImageTextureHeight = tangoCameraIntrinsics.height;
return true;
}
bool TangoHandler::getCameraImageSize(uint32_t* width, uint32_t* height)
{
bool result = true;
*width = cameraImageWidth;
*height = cameraImageHeight;
return result;
}
bool TangoHandler::getCameraImageTextureSize(uint32_t* width, uint32_t* height)
{
bool result = true;
*width = cameraImageTextureWidth;
*height = cameraImageTextureHeight;
return result;
}
bool TangoHandler::getCameraFocalLength(double* focalLengthX, double* focalLengthY)
{
bool result = true;
*focalLengthX = tangoCameraIntrinsics.fx;
*focalLengthY = tangoCameraIntrinsics.fy;
return result;
}
bool TangoHandler::getCameraPoint(double* x, double* y)
{
bool result = true;
*x = tangoCameraIntrinsics.cx;
*y = tangoCameraIntrinsics.cy;
return result;
}
bool TangoHandler::updateCameraImageIntoTexture(uint32_t textureId)
{
if (!connected) return false;
TangoErrorType result = TangoService_updateTextureExternalOes(TANGO_CAMERA_COLOR, textureId, &lastTangoImageBufferTimestamp);
std::time(&lastTangoImagebufferTimestampTime);
// LOGI("JUDAX: TangoHandler::updateCameraImageIntoTexture lastTangoImageBufferTimestamp = %lf, result = %d, textureId = %d", lastTangoImageBufferTimestamp, result, textureId);
return result == TANGO_SUCCESS;
}
int TangoHandler::getSensorOrientation() const
{
return sensorOrientation;
}
int TangoHandler::getActivityOrientation() const
{
return activityOrientation;
}
bool TangoHandler::hasLastTangoImageBufferTimestampChangedLately()
{
std::time_t currentTime;
std::time(¤tTime);
return std::difftime(currentTime, lastTangoImagebufferTimestampTime) < 1.0;
}
} // namespace tango_chromium
<file_sep># WebARonARCore
**An experimental app for Android that lets developers create Augmented Reality (AR) experiences using web technologies.**
**Note:** This is not an official Google product. Nor is it a fully-featured web browser. Nor are the enabling JavaScript APIs standards, or on the standardization path. WebARonARCore is only meant to enable developer experimentation.
An [iOS version](https://github.com/google-ar/WebARonARKit) is also available.
## <a name="SupportedDevices">Supported devices</a>
WebARonARCore is built on top of Android [ARCore](https://developers.google.com/ar), which requires an ARCore-compatible Android device. For best results, we recommend:
* Google Pixel or Pixel XL
* Samsung Galaxy S8
## <a name="Getting started">Getting started</a>
### Install the ARCore APK
In order to use ARCore you need to install the ARCore APK first.
#### Directly from a device
* Open an web browser on your Android device.
* Open this page and click [here](https://github.com/google-ar/arcore-android-sdk/releases/download/sdk-preview/arcore-preview.apk) to download and install the ARCore APK directly.
#### Using ADB
* Download the ARCore APK to your computer form [here](https://github.com/google-ar/arcore-android-sdk/releases/download/sdk-preview/arcore-preview.apk).
* Install the ARCore APK to your device: `$ adb install -r arcore_preview.apk`
### Install the WebARonARCore APK
Once ARCore is installed, WebARonARCore can be [installed from a prebuilt APK](#InstallingAPK), or [built from source](#CompileFromSource).
#### <a name="InstallingAPK">Option 1: Install the prebuilt WebARonARCore APK</a>
We have provided a prebuilt APK for your convenience inside this repo. You can install it:
##### Directly from a device
* Open an web browser on your Android device.
* Open this page and click [here](https://github.com/google-ar/WebARonARCore/raw/webarcore_57.0.2987.5/apk/WebARonARCore.apk) to download and install the WebARonARCore APK directly.
* Launch the WebARonARCore app from your device.
##### Using ADB
* Download the WebARonARCore APK from [here](https://github.com/google-ar/WebARonARCore/blob/webarcore_57.0.2987.5/apk/WebARonARCore.apk).
* Install the WebARonARCore APK to your device: `$ adb install -r WebARonARCore.apk`
* Launch the WebARonARCore app from your device.
#### <a name="CompileFromSource">Option 2: Build the WebARonARCore APK from source</a>
##### Clone the git repo and prepare it to be built
Instructions for [cloning and building Chromium](https://www.chromium.org/developers/how-tos/android-build-instructions) are available at [chromium.org](https://www.chromium.org/developers/how-tos/android-build-instructions)
Prerequisites:
* Linux machine
* GIT
* Python
We recommend you follow the following steps.
1. Open a terminal window
2. Install depot_tools. You can follow this [tutorial](https://commondatastorage.googleapis.com/chrome-infra-docs/flat/depot_tools/docs/html/depot_tools_tutorial.html#_setting_up) or simply follow these 2 steps:
* `git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git`
* `export PATH=$PATH:/path/to/depot_tools`
3. Create a folder to contain `chromium` and move to it: `$ mkdir ~/chromium && cd ~/chromium`
4. Checkout the Chromium repo: `~/chromium$ fetch --nohooks android`. **Note**: This process may take a long time (an hour?)
5. Enter the `src` folder: `$ cd src`.
6. Add this git repo as a remote (we are going to call it 'github'): `git remote add github https://github.com/google-ar/WebARonARCore.git`
7. Fetch the newly added remote: `git fetch github`
8. Checkout the webarcore branch from the github remote: `git checkout --track github/webarcore_57.0.2987.5`
9. Synchronize the dependencies with this command: `~/chromium/src$ gclient sync --disable-syntax-validation`. **Note**: This process may take some time too.
10. Create a folder where to make the final product compilation: `~/chromium/src$ mkdir -p out/master` (you will need to create a folder matching the name of your branch, in this case `webarcore_57.0.2987.5`).
11. Create and edit a new file `out/webarcore_57.0.2987.5/args.gn`. Copy and paste the following content in the `args.gn` file:
```
target_os = "android"
target_cpu = "arm64"
is_debug = false
is_component_build = true
enable_webvr = true
proprietary_codecs = false
ffmpeg_branding = "Chromium"
enable_nacl = false
remove_webcore_debug_symbols = true
```
12. Prepare to build: `~/chromium/src$ gn args out/webarcore_57.0.2987.5`. **Note**: once the command is executed, the vi editor will show you the content of the `args.gn` file just edited a few steps before. Just exit by pressing ESC and typing colon and `x`.
13. Install the build dependencies: `~/chromium/src$ build/install-build-deps-android.sh`
14. Synchronize the resources once again: `~/chromium/src$ gclient sync --disable-syntax-validation`
15. Setup the environment: `~/chromium/src$ . build/android/envsetup.sh`
##### 2. Build, install and run
The line below not only compiles Chromium but also installs the final APK on to a connected device and runs it, so it is convenient that you to connect the device via USB before executing it. The project that will be built by default is the Chromium WebView project, the only one that has been modified to provide AR capabilities.
```
~/chromium/src$ ./build_install_run.sh
```
You can review the content of the script to see what it does (it is a fairly simple script) but if you would like to compile the final APK on your own you could do it by executing the following command:
```
~/chromium/src$ ninja -C out/webarcore_57.0.2987.5
```
The final APK will be built in the folder `~/chromium/src/out/webarcore_57.0.2987.5/apks`.
## <a name="ViewingExamples">Viewing examples</a>
A [list of examples](https://developers.google.com/ar/develop/web/getting-started#examples) is available at [developers.google.com](https://developers.google.com/ar/develop/web/getting-started#examples).
## <a name="BuildingScenes">Building your own scenes</a>
[Instructions](https://developers.google.com/ar/develop/web/getting-started) for creating your own experiences are available at [developer.google.com](https://developers.google.com/ar/develop/web/getting-started).
## <a name="HowWebARonARCoreWorks">How WebARonARCore works</a>
WebARonARCore is built of two essential technologies: ARCore and Chromium. We also extend the WebVR 1.1 API, which gives us much of what we need for augmented reality, with a few more essentials, such as motion tracking, rendering of the camera's video feed, and basic understanding of the real world. For details, see [WebVR API extension for smartphone AR](https://github.com/google-ar/three.ar.js/blob/master/webvr_ar_extension.md)
## <a name="KnownIssues">Known issues</a>
* The current implementation of WebAR is built on top of the Chromium WebView flavor. This has some implementation advantages but some performance and use disadvantages. We are working on making the implementation on a full version of Chromium.
* Pausing/resuming/switching away from the app causes screen to turn black. This is a consequence of having built the implementation on top of the WebView flavor of Chromium. A proper implementation on full Chromium or a rebase to a more recent Chromium WebView version (>57.0.2987.5) might solve this problem.
## <a name="FutureWork">Future work</a>
* Add more AR-related features.
* Adapt the implementation to the WebVR 2.0 spec proposal.
* Implement the prototype on full Chromium (not on the WebView flavor) and to a newer tag version (>57.0.2987.5).
* Improve the VRPassThroughCamera rendering pipeline either making it obscure for the developer or by using regular WebGL textures and shader samplers without having to use the external image texture extension.
## <a name="License">License</a>
Apache License Version 2.0 (see the `LICENSE` file inside this repo).
<file_sep>/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _TANGO_HANDLER_H_
#define _TANGO_HANDLER_H_
#include "tango_client_api.h" // NOLINT
#include "tango_client_api2.h" // NOLINT
#include "tango_support.h" // NOLINT
#include <ctime>
#include <jni.h>
#include <android/log.h>
#include <string>
#include <vector>
#include <queue>
#include <mutex>
#define LOG_TAG "LeTango Chromium"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
namespace tango_chromium {
class Hit
{
public:
float modelMatrix[16];
};
// TangoHandler provides functionality to communicate with the Tango Service.
class TangoHandler {
public:
static TangoHandler* getInstance();
static void releaseInstance();
TangoHandler();
TangoHandler(const TangoHandler& other) = delete;
TangoHandler& operator=(const TangoHandler& other) = delete;
~TangoHandler();
void onCreate(JNIEnv* env, jobject activity, int activityOrientation, int sensorOrientation);
void onTangoServiceConnected(JNIEnv* env, jobject tango);
void onPause();
void onDeviceRotationChanged(int activityOrientation, int sensorOrientation);
void onTangoEventAvailable(const TangoEvent* event);
bool isConnected() const;
bool getPose(TangoPoseData* tangoPoseData);
bool getProjectionMatrix(float near, float far, float* projectionMatrix);
bool hitTest(float x, float y, std::vector<Hit>& hits);
void resetPose();
bool updateCameraIntrinsics();
bool getCameraImageSize(uint32_t* width, uint32_t* height);
bool getCameraImageTextureSize(uint32_t* width, uint32_t* height);
bool getCameraFocalLength(double* focalLengthX, double* focalLengthY);
bool getCameraPoint(double* x, double* y);
bool updateCameraImageIntoTexture(uint32_t textureId);
int getSensorOrientation() const;
int getActivityOrientation() const;
private:
void connect();
void disconnect();
bool hasLastTangoImageBufferTimestampChangedLately();
static TangoHandler* instance;
bool connected;
TangoConfig tangoConfig;
TangoCameraIntrinsics tangoCameraIntrinsics;
double lastTangoImageBufferTimestamp;
std::time_t lastTangoImagebufferTimestampTime;
uint32_t cameraImageWidth;
uint32_t cameraImageHeight;
uint32_t cameraImageTextureWidth;
uint32_t cameraImageTextureHeight;
bool textureIdConnected;
int activityOrientation;
int sensorOrientation;
std::string tangoCoreVersionString;
};
} // namespace tango_4_chromium
#endif // _TANGO_HANDLER_H_
<file_sep>/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "TangoHandler.h"
using namespace tango_chromium;
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL
Java_org_chromium_android_1webview_shell_TangoJniNative_cacheJavaObjects(
JNIEnv* env, jobject, jobject jTangoUpdateCallback) {
LOGE("Java_org_chromium_android_1webview_shell_TangoJniNative_cacheJavaObjects 1");
TangoService_CacheJavaObjects(env, jTangoUpdateCallback);
LOGE("Java_org_chromium_android_1webview_shell_TangoJniNative_cacheJavaObjects 2");
}
JNIEXPORT void JNICALL
Java_org_chromium_android_1webview_shell_TangoJniNative_onCreate(JNIEnv* env, jobject obj, jobject caller_activity, jint activityOrientation, jint sensorOrientation)
{
TangoHandler::getInstance()->onCreate(env, caller_activity, activityOrientation, sensorOrientation);
}
JNIEXPORT void JNICALL
Java_org_chromium_android_1webview_shell_TangoJniNative_onDestroy(JNIEnv* env, jobject obj)
{
TangoHandler::releaseInstance();
}
JNIEXPORT void JNICALL
Java_org_chromium_android_1webview_shell_TangoJniNative_onTangoServiceConnected(JNIEnv* env, jobject, jobject tango)
{
TangoHandler::getInstance()->onTangoServiceConnected(env, tango);
}
JNIEXPORT void JNICALL
Java_org_chromium_android_1webview_shell_TangoJniNative_onPause(JNIEnv*, jobject)
{
TangoHandler::getInstance()->onPause();
}
JNIEXPORT void JNICALL
Java_org_chromium_android_1webview_shell_TangoJniNative_onConfigurationChanged(JNIEnv*, jobject, int activityOrientation, int sensorOrientation)
{
TangoHandler::getInstance()->onDeviceRotationChanged(activityOrientation, sensorOrientation);
}
JNIEXPORT void JNICALL
Java_org_chromium_android_1webview_shell_TangoJniNative_onTextureAvailable(
JNIEnv* env, jobject, jint cameraId) {
TangoService_JavaCallback_OnTextureAvailable(static_cast<int>(cameraId));
}
JNIEXPORT void JNICALL
Java_org_chromium_android_1webview_shell_TangoJniNative_onImageAvailableCallback(
JNIEnv* env, jobject, jobject image, jobject metadata, jint cameraId) {
TangoService_JavaCallback_OnImageAvailable(env, static_cast<int>(cameraId),
image, metadata);
}
JNIEXPORT void JNICALL
Java_org_chromium_android_1webview_shell_TangoJniNative_onTangoEventCallback(
JNIEnv* env, jobject, jobject event) {
TangoService_JavaCallback_OnTangoEvent(env, event);
}
JNIEXPORT void JNICALL
Java_org_chromium_android_1webview_shell_TangoJniNative_resetPose(
JNIEnv* env, jobject, jobject event) {
TangoHandler::getInstance()->resetPose();
}
#ifdef __cplusplus
}
#endif
|
3bef0f4f9a82df9e6830da00ae09af257fa4978b
|
[
"Markdown",
"C++"
] | 5
|
C++
|
Hansuku/WebARonARCore
|
d441e5d41243f30d5f6d05edf4a2dbf72ce711ed
|
9160c910d5ad5e011f4fc13d257390ce46c78526
|
refs/heads/master
|
<file_sep># ztable
ztable is a library for handling hash tables in C. It is intended as a drop-in two-file library that takes little work to setup and teardown, and even less work to integrate into a project of your own.
## Installation
To keep things simple, there will probably never be an official package for this. ztable will build on any Unix based platform with whatever compiler you choose.
ztable can be built with:
`gcc -Wall -Werror -std=c99 ztable.c main.c
## Usage
An example of working with strings mapped to integers is below.
<pre>
void save_integers_to_table() {
//Define some data
const char *data[] = { "one", "two", "three", "four", "five" };
const char **d = data;
//The zTable structure can be allocated either dynamically or statically
zTable *t = malloc( sizeof( zTable ) );
//However, the structure's initialization will usually be dynamic.
lt_init( t, NULL, 1024 );
//To add keys we can loop through a list, generating integers along the way.
while ( *d ) {
// w will start at zero, and we'll add 13 at each new iteration
static int w;
//Add a text key (must be a zero-terminated string)
lt_addtextkey( t, *d );
//Add a numeric value.
//NOTE: Strings, BLOBs and void * are also supported via other functions.
lt_addintvalue( t, w );
//Terminate the "row" with lt_finalize
lt_finalize( t );
//Increment our numeric count and move to the next string in **d
w += 13;
y++;
}
//Finally, to get hashing to work, use lt_lock( ... )
lt_lock( t );
}
</pre>
To retrieve values from our table, we can use either `lt_geti` or `lt_$TYPE` where $TYPE can be `text`, `int`, `float`, `blob` or `userdata`. `lt_geti` acts as a check function, which simply checks the table for a particular key and returns a positive integer if present.
The `lt_$TYPE` family are convenience functions and will attempt to return the most appropriate value possible for non-existent values. In other words, if a key supplied to `lt_text(...)` does not exist, `lt_text(...)` will return NULL. Most of the time a zero or NULL value is the right thing, but a caveat to this is discovered when taking a closer look at `lt_int` and `lt_float`. Both functions return 0 in the case of keys that aren't found. For this reason, it's best to check the existence of the key first with `lt_geti`.
Using our example from above, let's look for the values 'one' and 'hot'.
<pre>
int val1 = lt_int( t, "one" );
int val2 = lt_int( t, "hot" );
fprintf( stderr, "val1: %d\n", val1 );
fprintf( stderr, "val2: %d\n", val2 );
</pre>
Outputs
<pre>
val1: 26
val2: 0
</pre>
Note that unless when using NULL as the middle argument to `lt_init`, there will always be data to free. So using `lt_free` will destroy the table data.
<pre>
lt_free( t );
</pre>
Likewise, if the zTable structure was dynamically allocated, don't forget to free it.
<pre>
free( t );
</pre>
Tables can be statically initialized as well by manually specifying the modulo value and an array of the datatype zKeyval. In other words, instead of:
<pre>
lt_init( t, NULL, 1024 );
</pre>
do:
<pre>
zKeyval kv[1024] = { 0 };
lt_init( t, kv, sizeof( kv ) );
</pre>
As stated earlier, strings and integers are not the only values that ztable supports. ztable can map strings to integers, other strings, blobs and void pointers, allowing whatever you want to fit into a slot. Better support (read <i>typesafe</i>) for more abstract datatypes will probably end up here in the future.
## Reference
### Simple
To get busy using ztable as a hash table, only the following functions are really needed.
#### Initialization & Teardown
`zTable * lt_init ( zTable * , zKeyval * , int )`
- Initialize the zTable either dynamically or statically.
`void lt_lock ( zTable * )`
- Initialize hashes for each key. Use this after all of the values you want in the table have been added.
`void lt_free( zTable * )`
- Destroy a zTable
#### Adding Values
`zhType lt_addintkey(t, v)`
- Add an integer key. Return value can be discarded.
`zhType lt_addintvalue(t, v)`
- Add an integer value. Return value can be discarded.
`zhType lt_addtextkey(t, v)`
- Add an zero-terminated string key. Strings added in this manner are duplicated by ztable.
`zhType lt_addtextvalue(t, v)`
- Add an zero-terminated string value. Strings added in this manner are duplicated by ztable.
`zhType lt_addblobvalue(t, vblob, vlen)`
- Add a BLOB value where vblob is an unsigned char * and vlen is its length. Return value can be discarded.
`zhType lt_addfloatvalue(t, v)`
- Add an float value. Return value can be discarded.
`zhType lt_addudvalue(t, v)`
- Add an opaque value. Return value can be discarded.
`void lt_finalize ( zTable * ) `
- Finalize a key-value set in a zTable. Use this after adding at least one key and one value.
`void lt_descend( t )`
- Create a "table" within a zTable
`void lt_ascend( t )`
- Ascend from a "table" within a zTable (lt_finalize is not needed after calling this)
#### Retrieving Values
`int lt_geti ( zTable * , char * )`
- Check that a string key is present in a zTable.
`int lt_get_long_i ( zTable * , unsigned char * , int)`
- Check that an unsigned char * block matches a key in a zTable.
`int lt_int( zTable *, const char * )`
- Retrieve an integer value from a zTable. Returns 0 if value does not exist.
`float lt_float( zTable *, const char * )`
- Retrieve an float value from a zTable. Returns 0 if value does not exist.
`char * lt_text( zTable *, const char * )`
- Retrieve a signed character value from a zTable. Returns NULL if value does not exist.
`zhBlob * lt_blob( zTable *, const char * )`
- Retrieve a zhBlob value from a zTable. Returns NULL if value does not exist.
`void *lt_userdata( zTable *, const char * )`
- Retrieve an opaque pointer value from a zTable. Returns NULL if value does not exist.
### Helpers
This functions exist to make dealing with text-based and binary data a little bit easier.
`unsigned char * lt_trim ( uint8_t * , char * , int, int * )`
- Trims whitespace found in a returned unsigned char * value.
### Advanced
These functions will help write iterators.
`int lt_exec_complex( zTable * , int, int, void * , int ( * fp)(zKeyval * , int, void * ) )` -
Base iterator function for acting on the elements in a zTable.
`int lt_counti(t, i)` -
Get a count of the elements at index <i>i</i>.
`int lt_counta(t, i)` -
Get an actual count of the elements at index <i>i</i>.
<!-- `zKeyval * lt_next( zTable * )` - -->
<!-- Return the zKeyval -->
<!-- `zKeyval * lt_current( zTable * )` - -->
<!-- Return the zKeyval -->
<!-- `void lt_reset( zTable * )` - -->
<!-- Reset the pointer -->
<!-- `int lt_exists ( zTable * , int)` - -->
<!-- const char * lt_strerror( zTable * ); -->
<!-- void lt_clearerror( zTable * ); -->
<!-- int lt_count_at_index ( zTable * , int, int); -->
<!-- int lt_countall ( zTable * ); -->
<!-- int lt_count_elements ( zTable * , int); -->
<!-- zKeyval *lt_retkv (zTable *, int); -->
<!-- zhType lt_rettype (zTable *, int, int); -->
<!-- const char *lt_rettypename (zTable *, int, int); -->
<!-- unsigned char *lt_get_full_key (zTable *, int, unsigned char *, int); -->
<!-- int lt_set (zTable *, int); -->
<!-- int lt_absset (zTable *, int); -->
<!-- int lt_get_raw (zTable *, int); -->
<!-- zhValue *lt_retany (zTable *, int ); -->
<!-- zhRecord *lt_ret (zTable *, zhType, int ); -->
<!-- void lt_setsrc (zTable *, void *); -->
<!-- zKeyval *lt_items_i (zTable *, uint8_t *, int); -->
<!-- zKeyval *lt_items_by_index (zTable *, int); -->
<!-- const char *lt_typename (int); -->
## Notes
ztable was extracted from a much larger library of mine called <a href="https://github.com/zaiah-dj/single">single.c</a>. Much of that library has no use now, but this is one of the pieces that has found its way into my recent projects.
<file_sep>#include "ztable.h"
const char *list[] = {
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
NULL
};
//...
struct inc { int depth; const char *key; float val; } inc_list[] = {
{ 0, "Basic Industries", 0 },
{ 1, "Aduro Biotech, Inc.", 5.24 },
{ 1, "AdvisorShares Vice ETF", 15.8 },
{ 1, "Aehr Test Systems", 0.8443 },
{ 0, "Capital Goods", 0 },
{ 1, "9F Inc.", 54.98 },
{ 1, "Acasti Pharma, Inc.", 8.76 },
{ 1, "Advanced Emissions Solutions, Inc.", 66.1 },
{ 1, "Aeglea BioTherapeutics, Inc.", 1.66 },
{ 1, "Aerie Pharmaceuticals, Inc.", 70.16 },
{ 1, "AEterna Zentaris Inc.", 1.27 },
{ 0, "Consumer Non-Durables", 0 },
{ 1, "Acorda Therapeutics, Inc.", 10.11 },
{ 1, "Act II Global Acquisition Corp.", 0.995 },
{ 1, "Act II Global Acquisition Corp.", 10.62 },
{ 0, "Consumer Services", 0 },
{ 1, "180 Degree Capital Corp.", 22.54 },
{ 1, "Addus HomeCare Corporation", 1.78 },
{ 1, "Affimed N.V.", 18.05 },
{ 1, "AGM Group Holdings Inc.", 13.49 },
{ 0, "Energy", 0 },
{ 1, "ABIOMED, Inc.", 0.2061 },
{ 0, "Finance", 0 },
{ 1, "111, Inc.", 4.5307 },
{ 1, "1347 Property Insurance Holdings, Inc.", 1.57 },
{ 1, "1347 Property Insurance Holdings, Inc.", 23.8 },
{ 1, "1-800-FLOWERS.COM, Inc.", 8.6 },
{ 1, "1Life Healthcare, Inc.", 13.11 },
{ 1, "1st Constitution Bancorp (NJ)", 36.56 },
{ 1, "2U, Inc.", 9.86 },
{ 1, "89bio, Inc.", 10.03 },
{ 1, "8i Enterprises Acquisition Corp", 0.29 },
{ 1, "8i Enterprises Acquisition Corp", 0.3492 },
{ 1, "8i Enterprises Acquisition Corp", 10.6 },
{ 1, "9 Meters Biopharma, Inc.", 5.9208 },
{ 1, "ACADIA Pharmaceuticals Inc.", 9.97 },
{ 1, "Acamar Partners Acquisition Corp.", 0.4801 },
{ 1, "Acamar Partners Acquisition Corp.", 10.2 },
{ 1, "ACM Research, Inc.", 26.26 },
{ 1, "Afya Limited", 10.1 },
{ 1, "AGBA Acquisition Limited", 0.08 },
{ 1, "AGBA Acquisition Limited", 0.2 },
{ 1, "AGBA Acquisition Limited", 10.22 },
{ 0, "Health Care", 0 },
{ 1, "10x Genomics, Inc.", 7.64 },
{ 1, "1895 Bancorp of Wisconsin, Inc.", 31.23 },
{ 1, "51job, Inc.", 26 },
{ 1, "8x8 Inc", 0.5999 },
{ 1, "AAON, Inc.", 3.3 },
{ 1, "Abeona Therapeutics Inc.", 207.76 },
{ 1, "Abraxas Petroleum Corporation", 7.71 },
{ 1, "Acacia Research Corporation", 28.8 },
{ 1, "Acadia Healthcare Company, Inc.", 50.63 },
{ 1, "Acamar Partners Acquisition Corp.", 0.6449 },
{ 1, "Accelerated Pharma, Inc.", 99.51 },
{ 1, "Acceleron Pharma Inc.", 2.18 },
{ 1, "Accuray Incorporated", 1.555 },
{ 1, "AcelRx Pharmaceuticals, Inc.", 3.38 },
{ 1, "Acer Therapeutics Inc.", 0.4105 },
{ 1, "ACI Worldwide, Inc.", 1.34 },
{ 1, "ACNB Corporation", 0.79 },
{ 1, "Activision Blizzard, Inc", 2.81 },
{ 1, "Adamas Pharmaceuticals, Inc.", 0.5025 },
{ 1, "Adamis Pharmaceuticals Corporation", 16.63 },
{ 1, "AdaptHealth Corp. ", 4.78 },
{ 1, "Adaptimmune Therapeutics plc", 39.08 },
{ 1, "Adaptive Biotechnologies Corporation", 7.28 },
{ 1, "Addex Therapeutics Ltd", 97.37 },
{ 1, "Adesto Technologies Corporation", 1.7 },
{ 1, "Adial Pharmaceuticals, Inc", 0.2102 },
{ 1, "Adial Pharmaceuticals, Inc", 3.03 },
{ 1, "ADTRAN, Inc.", 3.28 },
{ 1, "Advanced Micro Devices, Inc.", 0.71 },
{ 1, "Advaxis, Inc.", 21.02 },
{ 1, "Aegion Corp", 9.04 },
{ 1, "Aemetis, Inc", 14.39 },
{ 1, "AeroVironment, Inc.", 0.782 },
{ 1, "Aerpio Pharmaceuticals, Inc.", 7.79 },
{ 1, "Aesthetic Medical International Holdings Group Ltd.", 1.15 },
{ 1, "Aethlon Medical, Inc.", 3.16 },
{ 1, "AGBA Acquisition Limited", 2.75 },
{ 1, "Agenus Inc.", 3.19 },
{ 1, "Agilysys, Inc.", 53.04 },
{ 0, "Miscellaneous", 0 },
{ 1, "360 Finance, Inc.", 6.8 },
{ 1, "Acacia Communications, Inc.", 2.57 },
{ 0, "n/a", 0 },
{ 1, "Accelerate Diagnostics, Inc.", 832 },
{ 1, "Adverum Biotechnologies, Inc.", 19.0558 },
{ 1, "AdvisorShares Dorsey Wright Alpha Equal Weight ETF", 26.5849 },
{ 1, "AdvisorShares Dorsey Wright FSM All Cap World ETF", 25.7884 },
{ 1, "AdvisorShares Dorsey Wright FSM US Core ETF", 20.4729 },
{ 1, "AdvisorShares Dorsey Wright Micro-Cap ETF", 21.29 },
{ 1, "AdvisorShares Dorsey Wright Short ETF", 23.0243 },
{ 0, "Public Utilities", 0 },
{ 1, "Adobe Inc.", 11.38 },
{ 0, "Technology", 0 },
{ 1, "1st Source Corporation", 15.14 },
{ 1, "21Vianet Group, Inc.", 34.89 },
{ 1, "36Kr Holdings Inc.", 62.88 },
{ 1, "8i Enterprises Acquisition Corp", 15.49 },
{ 1, "Achieve Life Sciences, Inc. ", 27.35 },
{ 1, "AC Immune SA", 67.25 },
{ 1, "Aclaris Therapeutics, Inc.", 59.16 },
{ 1, "Act II Global Acquisition Corp.", 70.15 },
{ 1, "ADDvantage Technologies Group, Inc.", 12 },
{ 1, "ADMA Biologics Inc", 375.17 },
{ 1, "Advanced Energy Industries, Inc.", 52.74 },
{ 1, "Agile Therapeutics, Inc.", 20.1 },
{ 1, "Agios Pharmaceuticals, Inc.", 20.89 },
{ 0, NULL }
};
struct yakvs { const char *key; char *val; } yakvs_list[] = {
{ "nobody", "knows" },
{ "the", "trouble I've seen." },
{ "Anthony", "Hopkins" },
{ "Mike", "Tyson" },
{ NULL }
};
int main (int argc, char *argv[]) {
//The ztable_t structure can be allocated either dynamically or statically
ztable_t *t = malloc( sizeof( ztable_t ) );
//However, the structure's initialization will usually be dynamic.
lt_init( t, NULL, 1024 );
//To statically initialize the structure, we'll use an array of zKeyvals
//zKeyval kv[1024] = { 0 };
//To add values we can loop through a list.
fprintf( stderr, "SHORT WORDS\n============\n" );
fprintf( stderr, "Out of a set of 4 words, let's find some values.\n" );
struct yakvs *y = yakvs_list;
while ( y->key ) {
lt_addtextkey( t, y->key );
lt_addtextvalue( t, y->val );
lt_finalize( t );
y++;
}
//Finally, to fully initialize the table, use lt_lock( ztable_t *t )
lt_lock( t );
//And for the purposes of this test, we'll see where hashes are...
lt_dump( t );
//Get the values
char *key1 = "the";
int hash = lt_geti( t, key1 );
fprintf( stderr, "hash of '%s': %d\n", key1, hash );
char *the = lt_text( t, key1 );
fprintf( stderr, "'%s' => %s\n", key1, the );
//When done, free the table with lt_free and free our allocation
lt_free( t );
free( t );
//Let's try another example, with random values on the other side...
const char **name = list;
int i = 0;
ztable_t *tt = malloc( sizeof( ztable_t ) );
lt_init( tt, NULL, 1024 );
fprintf( stderr, "\nPRESIDENTS\n============\n" );
fprintf( stderr, "Now we're importing a list of the first 45 U.S. presidents\n\n" );
while ( *name ) {
lt_addtextkey( tt, *name );
lt_addintvalue( tt, i );
lt_finalize( tt );
i += 3;
name++;
}
//Lock the table to initialize hashes
lt_lock( tt );
//Then dump it for our purposes
lt_dump( tt );
//Get the values
char key2[] = "Thomas Jefferson";
int xhash = lt_geti( tt, key2 );
fprintf( stderr, "hash of '%s': %d\n", key2, xhash );
int tj = lt_int( tt, key2 );
fprintf( stderr, "'%s' => %d\n", key2, tj );
//Again we free the table with lt_free and free our allocation
lt_free( tt );
free( tt );
//Last, let's add all of this and test tables...
fprintf( stderr, "\nCOPYINIG\n============\n" );
fprintf( stderr, "Now let's import a huge list of companies that are already sorted by category. Our table will contain a set of entries for each category\n\n" );
struct inc *inc = inc_list;
int key = 0;
//Initialize a big table
ztable_t *mt = malloc( sizeof( ztable_t ) );
lt_init( mt, NULL, 2048 );
//Add a key and table to keep each of these entries in the same "namespace"
lt_addtextkey( mt, "companies" );
lt_descend( mt );
//Loop through the list
while ( inc->key ) {
if ( inc->depth ) {
lt_addtextkey( mt, inc->key );
lt_addfloatvalue( mt, inc->val );
lt_finalize( mt );
}
else {
if ( key == 1 ) {
lt_ascend( mt );
key = 0;
}
lt_addtextkey( mt, inc->key );
lt_descend( mt );
key = 1;
}
inc++;
}
//Complete the encompassing table.
lt_ascend( mt );
lt_finalize( mt );
//Lock to initialize each hash
lt_lock( mt );
//Dump the table
lt_dump( mt );
//Try copying multiple tables via lt_copy
ztable_t *cg_t, *fin_t;
//Pull the first one via an index
int findex = lt_geti( mt, "companies.Finance" );
fin_t = lt_copy_by_index( mt, findex );
fprintf( stderr, "Dump just the finance table (hash %d)\n", findex );
//No locking is necessary...
lt_dump( fin_t );
lt_free( fin_t );
free( fin_t );
//Then pull captial goods, notice we use a key
cg_t = lt_copy_by_key( mt, "companies.Capital Goods" );
fprintf( stderr, "Then dump just the 'Capital Goods' table.");
fprintf( stderr, " (We'll use a string this time)\n" );
lt_dump( cg_t );
lt_free( cg_t );
free( cg_t );
lt_free( mt );
free( mt );
return 0;
}
<file_sep>/* ----------------------------------------------------------------
* ztable.h
* ========
*
* Summary
* =======
* ztable is a library for handling hash tables in C. It is intended
* as a drop-in two-file library that takes little work to setup and teardown,
* and even less work to integrate into a project of your own.
*
* ztable can be built with:
* `gcc -Wall -Werror -std=c99 ztable.c main.c`
*
*
* LICENSE
* -------
* Copyright 2020-2021 Tubular Modular Inc. dba Collins Design
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* ---------------------------------------------------------------- */
#ifndef _WIN32
#define _POSIX_C_SOURCE 200809L
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <unistd.h>
#else
#include <io.h>
#define write(FD,C,CLEN) _write(FD, C, CLEN)
#endif
#ifndef ZTABLE_H
#define ZTABLE_H
#ifndef LT_DEVICE
#define LT_DEVICE 2
#endif
#define ZTABLE_ERRV_LENGTH 127
#define LT_BUFLEN 2047
#ifndef LT_MAX_COLLISIONS
#define LT_MAX_COLLISIONS 10
#endif
#define ztable_t zTable
#define lt_counti(t, i) \
lt_count_at_index( t, i, 1 )
#define lt_counta(t, i) \
lt_count_at_index( t, i, 0 )
#define lt_advance(t, pos) \
lt_set( t, pos )
#define lt_rewind(t, pos) \
lt_set( t, pos )
#define lt_exec(t, a, b) \
lt_exec_complex( t, 0, (t)->index, a, b )
#define lt_blob_at( t, i ) \
lt_ret( t, ZTABLE_BLB, i )->vblob
#define lt_blobdata_at( t, i ) \
lt_ret( t, ZTABLE_BLB, i )->vblob.blob
#define lt_blobsize_at( t, i ) \
lt_ret( t, ZTABLE_BLB, i )->vblob.size
#define lt_int_at( t, i ) \
lt_ret( t, ZTABLE_INT, i )->vint
#define lt_float_at( t, i ) \
lt_ret( t, ZTABLE_FLT, i )->vfloat
#define lt_text_at( t, i ) \
lt_ret( t, ZTABLE_TXT, i )->vchar
#define lt_userdata_at( t, i ) \
lt_ret( t, ZTABLE_USR, i )->vusrdata
#define lt_table_at( t, i ) \
lt_ret( t, ZTABLE_TBL, i )->vtable
#define lt_blob( t, key ) \
lt_ret( t, ZTABLE_BLB, lt_get_long_i(t, (unsigned char *)key, strlen(key)) )->vblob
#define lt_blobdata( t, key ) \
lt_ret( t, ZTABLE_BLB, lt_get_long_i(t, (unsigned char *)key, strlen(key)) )->vblob.blob
#define lt_blobsize( t, key ) \
lt_ret( t, ZTABLE_BLB, lt_get_long_i(t, (unsigned char *)key, strlen(key)) )->vblob.size
#define lt_int( t, key ) \
lt_ret( t, ZTABLE_INT, lt_get_long_i(t, (unsigned char *)key, strlen(key)) )->vint
#define lt_float( t, key ) \
lt_ret( t, ZTABLE_FLT, lt_get_long_i(t, (unsigned char *)key, strlen(key)) )->vfloat
#define lt_text( t, key ) \
lt_ret( t, ZTABLE_TXT, lt_get_long_i(t, (unsigned char *)key, strlen(key)) )->vchar
#define lt_userdata( t, key ) \
lt_ret( t, ZTABLE_USR, lt_get_long_i(t, (unsigned char *)key, strlen(key)) )->vusrdata
#define lt_table( t, key ) \
lt_ret( t, ZTABLE_TBL, lt_get_long_i(t, (unsigned char *)key, strlen(key)) )->vtable
#define lt_lblob( t, key, len ) \
lt_ret( t, ZTABLE_BLB, lt_get_long_i(t, (unsigned char *)key, len) )->vblob
#define lt_lblobdata( t, key, len ) \
lt_ret( t, ZTABLE_BLB, lt_get_long_i(t, (unsigned char *)key, len) )->vblob.blob
#define lt_lblobsize( t, key, len ) \
lt_ret( t, ZTABLE_BLB, lt_get_long_i(t, (unsigned char *)key, len) )->vblob.size
#define lt_lint( t, key, len ) \
lt_ret( t, ZTABLE_INT, lt_get_long_i(t, (unsigned char *)key, len) )->vint
#define lt_lfloat( t, key, len ) \
lt_ret( t, ZTABLE_FLT, lt_get_long_i(t, (unsigned char *)key, len) )->vfloat
#define lt_ltext( t, key, len ) \
lt_ret( t, ZTABLE_TXT, lt_get_long_i(t, (unsigned char *)key, len) )->vchar
#define lt_luserdata( t, key, len ) \
lt_ret( t, ZTABLE_USR, lt_get_long_i(t, (unsigned char *)key, len) )->vusrdata
#define lt_ltable( t, key, len ) \
lt_ret( t, ZTABLE_TBL, lt_get_long_i(t, (unsigned char *)key, len) )->vtable
#define lt_ascend( t ) \
lt_move( t, 1 )
#define lt_descend( t ) \
lt_move( t, 0 )
#define lt_geti( t, key ) \
lt_get_long_i( t, (unsigned char *)key, strlen((char *)key))
#define lt_keytype( t ) \
lt_rettype( t, 0, (t)->index )
#define lt_valuetype( t ) \
lt_rettype( t, 1, (t)->index )
#define lt_keytypename( t ) \
lt_rettypename( t, 0, (t)->index )
#define lt_valuetypename( t ) \
lt_rettypename( t, 1, (t)->index )
#define lt_keytypeat( t, i ) \
lt_rettype( t, 0, i )
#define lt_valuetypeat( t, i ) \
lt_rettype( t, 1, i )
#define lt_keytypenameat( t, i ) \
lt_rettypename( t, 0, i )
#define lt_valuetypenameat( t, i ) \
lt_rettypename( t, 1, i )
#define lt_kt( t ) \
lt_rettype( t, 0, (t)->index )
#define lt_vt( t ) \
lt_rettype( t, 1, (t)->index )
#define lt_ktn( t ) \
lt_rettypename( t, 0, (t)->index )
#define lt_vtn( t ) \
lt_rettypename( t, 1, (t)->index )
#define lt_kta( t, i ) \
lt_rettype( t, 0, i )
#define lt_vta( t, i ) \
lt_rettype( t, 1, i )
#define lt_ktna( t, i ) \
lt_rettypename( t, 0, i )
#define lt_vtna( t, i ) \
lt_rettypename( t, 1, i )
#define lt_addintkey(t, v) \
lt_add(t, 0, ZTABLE_INT, v, 0, 0, 0, 0, 0, 0, NULL)
#define lt_addintvalue(t, v) \
lt_add(t, 1, ZTABLE_INT, v, 0, 0, 0, 0, 0, 0, NULL)
#define lt_addtextkey(t, v) \
lt_add(t, 0, ZTABLE_TXT, 0, 0, 0, (unsigned char *)v, strlen(v), 0, 0, NULL)
#define lt_addtextvalue(t, v) \
lt_add(t, 1, ZTABLE_TXT, 0, 0, 0, (unsigned char *)v, strlen(v), 0, 0, NULL)
#define lt_addblobdkey(t, v, vlen) \
lt_add(t, 0, ZTABLE_TXT, 0, 0, 0, (unsigned char *)v, vlen, 0, 0, NULL)
#define lt_addblobdvalue(t, v, vlen) \
lt_add(t, 1, ZTABLE_TXT, 0, 0, 0, (unsigned char *)v, vlen, 0, 0, NULL)
#define lt_addblobkey(t, vblob, vlen) \
lt_add(t, 0, ZTABLE_BLB, 0, 0, 0, vblob, vlen, 0, 0, NULL)
#define lt_addblobvalue(t, vblob, vlen) \
lt_add(t, 1, ZTABLE_BLB, 0, 0, 0, vblob, vlen, 0, 0, NULL)
#define lt_addfloatvalue(t, v) \
lt_add(t, 1, ZTABLE_FLT, 0, v, 0, 0, 0, 0, 0, NULL)
#ifdef ZTABLE_NUL
#define lt_addnullvalue(t) \
lt_add(t, 1, ZTABLE_NUL, 0, 0, 0, 0, 0, 0, 0, NULL)
#endif
#define lt_addudvalue(t, v) \
lt_add(t, 1, ZTABLE_USR, 0, 0, 0, 0, 0, v, 0, NULL)
#define lt_addik(t, v) \
lt_add(t, 0, ZTABLE_INT, v, 0, 0, 0, 0, 0, 0, NULL)
#define lt_addiv(t, v) \
lt_add(t, 1, ZTABLE_INT, v, 0, 0, 0, 0, 0, 0, NULL)
#define lt_addtk(t, v) \
lt_add(t, 0, ZTABLE_TXT, 0, 0, 0, (unsigned char *)v, strlen(v), 0, 0, NULL)
#define lt_addtv(t, v) \
lt_add(t, 1, ZTABLE_TXT, 0, 0, 0, (unsigned char *)v, strlen(v), 0, 0, NULL)
#define lt_addbk(t, vblob, vlen) \
lt_add(t, 0, ZTABLE_BLB, 0, 0, 0, vblob, vlen, 0, 0, NULL)
#define lt_addbv(t, vblob, vlen) \
lt_add(t, 1, ZTABLE_BLB, 0, 0, 0, vblob, vlen, 0, 0, NULL)
#define lt_addfv(t, v) \
lt_add(t, 1, ZTABLE_FLT, 0, v, 0, 0, 0, 0, 0, NULL)
#ifdef ZTABLE_NUL
#define lt_addnv(t) \
lt_add(t, 1, ZTABLE_NUL, 0, 0, 0, 0, 0, 0, 0, NULL)
#endif
#define lt_adduv(t, v) \
lt_add(t, 1, ZTABLE_USR, 0, 0, 0, 0, 0, v, 0, NULL)
#define lt_addtbk(t, str, vblob, vlen) \
lt_add(t, 0, ZTABLE_BLB, 0, 0, 0, vblob, vlen, 0, 0, str)
#define lt_addtbv(t, str, vblob, vlen) \
lt_add(t, 1, ZTABLE_BLB, 0, 0, 0, vblob, vlen, 0, 0, str)
#define lt_items(t, str) \
lt_items_i(t, (unsigned char*)str, strlen((char *)str))
#define lt_iitems(t, ind) \
lt_items_by_index(t, ind )
#define lt_within( t, str ) \
lt_within_long( t, (unsigned char *)str, strlen(str))
#define lt_copy_by_key(t, start) \
lt_deep_copy (t, lt_geti( t, start ), t->count )
#define lt_copy_by_index(t, start) \
lt_deep_copy (t, start, t->count )
#ifndef DEBUG_H
#define lt_dump(t)
#define lt_fdump(t, i)
#define lt_kfdump(t, i)
#define lt_kdump(t)
#define lt_sdump(t)
#else
#define lt_dump(t) \
!( __ltHistoric.level = 0 ) && fprintf( stderr, "LEVEL IS %d\n", __ltHistoric.level ) && lt_exec( t, &__ltHistoric, __lt_dump )
#define lt_fdump(t, i) \
!( __ltHistoric.level = 0 ) && ( __ltHistoric.fd = i ) && lt_exec( t, &__ltHistoric, __lt_dump ) && fflush( stdout )
#define lt_kfdump(t, i) \
!( __ltComplex.level = 0 ) && ( __ltComplex.fd = i ) && lt_exec( t, &__ltComplex, __lt_dump ) && fflush( stdout )
#define lt_kdump(t) \
!( __ltComplex.level = 0 ) && lt_exec( t, &__ltComplex, __lt_dump )
#define lt_sdump(t) \
lt_exec( t, &__ltSimple, __lt_dump )
#endif
enum {
ZTABLE_ERR_NONE = 0,
ZTABLE_ERR_LT_ALLOCATE,
ZTABLE_ERR_LT_OUT_OF_SPACE,
ZTABLE_ERR_LT_INVALID_VALUE,
ZTABLE_ERR_LT_INVALID_TYPE,
ZTABLE_ERR_LT_INVALID_INDEX,
ZTABLE_ERR_LT_OUT_OF_SLICE,
ZTABLE_ERR_LT_MAX_COLLISIONS,
ZTABLE_ERR_LT_INVALID_KEY,
ZTABLE_ERR_LT_INDEX_MAX,
};
//Define a type polymorph with a bunch of things to help type inference
typedef struct zhValue zhValue;
typedef struct zhBlob zhBlob;
typedef struct zhTable zhTable;
typedef struct zKeyval zKeyval;
typedef union zhRecord zhRecord;
typedef struct {
enum { LT_DUMP_SHORT, LT_DUMP_LONG } dumptype;
char fd, level, *buffer;
} zhInner;
//Table for table values
typedef enum {
ZTABLE_NON = 0, //Uninitialized values
ZTABLE_INT, //Integer
ZTABLE_FLT, //FLoat
ZTABLE_TXT, //Text
ZTABLE_BLB, //Blobs (strings that don't terminate come back as blobs too)
ZTABLE_NUL, //Null
ZTABLE_USR, //Userdata
ZTABLE_TBL, //A "table"
ZTABLE_TRM, //Table terminator (NULL alone can't be described)
ZTABLE_NOD, //A node
} zhType;
typedef struct {
unsigned int total ; //Size allocated (the bound)
unsigned int index ; //Index to current element
unsigned int count ; //Elements in table
unsigned int *rCount; //Elements in current table
unsigned short modulo ; //Optimal modulus value for hashing
int mallocd; //An error occurred, read it...
int srcmallocd; //An error occurred, read it...
int size ; //Size of newly trimmed key or pointer
int cptr ; //Table will stop here
int start ; //Table bounds are here if "lt_within" is used
int end ;
int buflen ;
#ifdef DEBUG_H
int collisions;
#endif
unsigned char *src; //Source for when you need it
unsigned char *buf; //Pointer for trimmed keys and values
zKeyval *head; //Pointer to the first element
zhTable *current; //Pointer to the current element
void *ptr; //A random void pointer...
int error;
#ifdef ZTABLE_ERR_EXP
char errmsg[ ZTABLE_ERRV_LENGTH ];
#endif
} zTable;
struct zhTable {
unsigned int count;
long ptr;
zhTable *parent;
};
struct zhBlob {
int size;
unsigned char *blob;
};
union zhRecord {
int vint;
float vfloat;
char *vchar;
#ifdef ZTABLE_NUL
void *vnull;
#endif
void *vusrdata;
zhBlob vblob;
zhTable vtable;
long vptr;
};
struct zhValue {
zhType type;
zhRecord v;
};
struct zKeyval {
zhValue key;
zhValue value;
zKeyval *parent;
//This works b/c we can hash at lt_lock...
//Can't tell if there's a way to use allocation to get this done
int index[ LT_MAX_COLLISIONS ];
#ifdef DEBUG_H
//int collisions;
//int ???;
#endif
//zKeyval *next[ LT_MAX_COLLISIONS ];
//int hash[LT_MAX_COLLISIONS];
};
extern zhInner __ltComplex;
extern zhInner __ltHistoric;
extern zhInner __ltSimple;
zhType lt_add (zTable *, int, zhType,
int, float, char *, unsigned char *, unsigned int , void *, zTable *, char *);
zTable *lt_init (zTable *, zKeyval *, int) ;
zTable *lt_make ( int ) ;
void lt_printall (zTable *);
void lt_finalize (zTable *) ;
int __lt_dump (zKeyval *, int, void *);
int lt_exec_complex (zTable *, int, int, void *, int (*fp)(zKeyval *, int, void *) );
int lt_move(zTable *, int) ;
zKeyval *lt_retkv (zTable *, int);
zhType lt_rettype (zTable *, int, int);
const char *lt_rettypename (zTable *, int, int);
int lt_lock (zTable *);
int lt_get_long_i (zTable *, unsigned char *, int);
unsigned char *lt_get_full_key (zTable *, int, unsigned char *, int);
zKeyval *lt_next (zTable *);
zKeyval *lt_current (zTable *);
void lt_reset (zTable *);
int lt_set (zTable *, int);
int lt_absset (zTable *, int);
int lt_get_raw (zTable *, int);
zhValue *lt_retany (zTable *, int );
zhRecord *lt_ret (zTable *, zhType, int );
void lt_setsrc (zTable *, void *);
void lt_free (zTable *);
unsigned char *lt_trim (unsigned char *, char *, int, int *);
zKeyval *lt_items_i (zTable *, unsigned char *, int);
zKeyval *lt_items_by_index (zTable *, int);
int lt_count_elements ( zTable *, int);
int lt_exists (zTable *, int);
int lt_count_at_index ( zTable *, int, int);
int lt_countall ( zTable * );
zTable *lt_within_long( zTable *, unsigned char *, int);
const char *lt_typename (int);
zTable *lt_deep_copy (zTable *t, int from, int to);
const char *lt_strerror (zTable *);
void lt_clearerror (zTable *);
int build_backwards (zKeyval *, unsigned char *, int );
#ifdef DEBUG_H
void lt_printt (zTable *);
void lt_free_keys ( const char ** );
const char ** lt_get_keys ( zTable * );
#endif
#endif
<file_sep>NAME = ztable
LDFLAGS =
DFLAGS = -g -O0 -fsanitize=address -fsanitize-undefined-trap-on-error
CLANGFLAGS = -Wall -Werror -std=c99 -Wno-unused -Wno-format-security
GCCFLAGS = -Wall -Werror -std=c99 -Wno-unused -DLT_TABDUMP
CFLAGS = $(CLANGFLAGS)
CFLAGS = $(GCCFLAGS)
CC = clang
CC = gcc
PREFIX = /usr/local
VERSION = 0.01
test:
$(CC) $(CFLAGS) -DDEBUG_H -o $(NAME)-test $(NAME).c main.c
win: CC = clang
win: CFLAGS = $(CLANGFLAGS)
win:
$(CC) $(CFLAGS) -DDEBUG_H -o $(NAME)-test.exe $(NAME).c main.c
clang: CC = clang
clang: CFLAGS = $(CLANGFLAGS)
clang: test
@printf '' > /dev/null
debug: CC = clang
debug: CFLAGS += $(DFLAGS)
debug: test
@printf '' > /dev/null
clean:
@rm *.o $(NAME)-test*
|
21d99bf9cff349f1b420ad13e8e8d489e676aa09
|
[
"Markdown",
"C",
"Makefile"
] | 4
|
Markdown
|
zaiah-dj/zhasher
|
2a29afe889e39a29fbe2af3a95ce64ef58ea137a
|
a629eb250b5b19d114211310755c3d1c39f5a7ca
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Reflection;
using System.Runtime.Remoting.Proxies;
using System.Text;
using System.Threading.Tasks;
namespace TransparentProxyRequirements
{
class Program
{
static void Main(string[] args)
{
// this is how the code works on Android/Console projects
//ensure reactive extensions is loaded.
var observableType = typeof(Observable);
// we look at the hidden field s_impl to get the existing implementation for the query language interface
var field = observableType.GetField("s_impl", BindingFlags.Static | BindingFlags.NonPublic);
var originalInterceptor = field.GetValue(null);
// we create a transparent proxy for the original query language implementation
var interceptor = new QueryLanguageProxy(originalInterceptor).GetTransparentProxy();
// and assign the transparent proxy
field.SetValue(null,interceptor);
// now, all operations run through our transparent proxy.
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.Text;
using System.Threading.Tasks;
namespace TransparentProxyRequirements
{
public class QueryLanguageProxy:RealProxy, IRemotingTypeInfo
{
private readonly object _originalInterceptor;
public QueryLanguageProxy(object originalInterceptor): base(typeof(ContextBoundObject))
{
_originalInterceptor = originalInterceptor;
}
public override IMessage Invoke(IMessage msg)
{
// this is where we would log what happens
// and also invoke the actual message
throw new NotImplementedException();
}
public bool CanCastTo(Type fromType, object o)
{
return fromType.Name == "IQueryLanguage";
}
public string TypeName
{
get { return this.GetType().Name; } set { }
}
}
}
<file_sep>## Requirements
We are implementing a tracing and logging extension based for Reactive Extensions to make the logging and diagnosis of Reactive Extensions based solutions easier.
We already have a solution, heavily based on the work done in RxSpy, which works on Android.
What we are looking to do now is also make this available for iOS solutions.
## Background
All static extension methods on System.Reactive.Observable go through a private member of the Observable class that implements the private interface IQueryLanguage https://github.com/Reactive-Extensions/Rx.NET/blob/master/Rx.NET/Source/System.Reactive.Linq/Reactive/Linq/IQueryLanguage.cs .
We use private reflection to both locate and set the field but it seems impossible to create an implementation of this private IQueryLanguage without being a friend assembly to System.Reactive.Linq.
We get around this by using RealProxy https://msdn.microsoft.com/en-us/library/system.runtime.remoting.proxies.realproxy(v=vs.110).aspx, which is part of .NET remoting API and allows us to create a transparent proxy that the framework is happy to accept.
However, whilst RealProxy works fine with Android & 'normal' .NET solutions it won't work with iOS solutions, *groan*.
## How to Move Forward
So, how can we move forward?
A few options spring to mind, I don't know if any of these however are viable.
1. Get Reactive Extensions to make the IQueryLanguage interface public, this would seem to be the easiest/safest option.
2. Don't know if this is viable but - weave/adjust the existing Reactive Extensions Libraries to make the interface public?
3. Similarly, weave/Adjust the Reactive Extensions Libraries existing IQueryLanguage interface to in effect do what the StaticProxy for Fody does.
|
8808cd1c03e480438c5edff88ae6630116180aee
|
[
"Markdown",
"C#"
] | 3
|
C#
|
VistianOpenSource/Transparent-Proxy-Requirements
|
6f4025d7fab6b01c4e1381ec5cdb75ca356b09f6
|
37c56de43458e75b8980abb6efc12a6b74c7cfe9
|
refs/heads/main
|
<file_sep># Stock Trading Robot
These robots are built to trade stocks live using [Alpaca's stock trading API](https://alpaca.markets/?utm_source=google&utm_medium=cpc&utm_campaign=search_us_automated_trading&utm_content=branded&gclid=Cj0KCQiA5vb-BRCRARIsAJBKc6KKPJZ2-22WBKl-lfLceJCI2hEd_RYMShMP2wO_O3dIuTyqAOwykJQaApgMEALw_wcB).
## Moving Averages Robot
This robot monitors the market for buy and sell signals generated from the crossover of simple or exponential moving averages.
Upon execution of the code the user is asked to define:
1) Ticker to trade
2) Buying power or quantity of securities to use in trades
3) Type of moving averages to monitor for buy/sell signals
* 5, 8, 13 bar *exponential* moving average
* 5, 8, 13 bar *simple* moving average
4) Maximum number of trades to execute
* 2 - one buy, one sell
* 4 - two buys, two sells
* etc.
## Momentum Robot
Currently in developement.
#### Breakout Strategy
* Look at past highs and generate buy signals as soon as price manages to break out from its previous high
* Use dynamic lookback ranges based on volatility
* When volatility is high, look further back
* When low, look less
* Open short-term long position and use stop loss
#### Gap and Go Strategy
* Looks for overnight gappers and bets on continuation of that move
* Open Short-term long/short trade and use stop loss
#### Earnings/News Strategy
* Look at the most well known/liquid stocks that had earnings in the past few days
* Focus on stocks that have an especially negative reaction from the market (-2%)
* Open medium-term long position and use stop loss
<file_sep>from flask import Flask, render_template, url_for, request, redirect
from flask_cors import CORS
app = Flask(__name__)
@app.route("/")
def index():
return render_template("dashboard.html")
@app.route("/login")
def register_view():
return render_template("login.html")
@app.route("/register")
def login_view():
return render_template("register.html")
if __name__=="__main__":
app.run(host="0.0.0.0", port=80, debug=False)
<file_sep>import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev'
DATA
|
e40985d96345fc642d06441812cb9824f6d3bb97
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
webclinic017/Stock-Advisor
|
c2e9e8d8f9efa18f2c447a5adb48661b8108878e
|
a6508e5f59461ac5cd168d1a298aba68dbee0355
|
refs/heads/main
|
<file_sep>//
// ViewController.swift
// BMITest
//
// Created by 羅承志 on 2021/5/2.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var heightTextField: UITextField!
@IBOutlet weak var weightTextField: UITextField!
@IBOutlet weak var BMILabel: UILabel!
@IBOutlet weak var BMIButton: UIButton!
@IBOutlet weak var adviceLabel: UILabel!
var changeBMI = Double(0)
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func BMICountButton(_ sender: Any) {
let heightText = heightTextField.text!
let weightText = weightTextField.text!
let height = Double(heightText)
let weight = Double(weightText)
if height != nil, weight != nil {
let heightMeter = height! / 100
let BMI = weight! / (heightMeter * heightMeter)
BMILabel.text = String(format: "%.2f", BMI)
}
//身體質量指數
changeBMI = Double(BMILabel.text!)!
if changeBMI <= 18.5 {
adviceLabel.text = "體重過輕"
} else if changeBMI <= 24 {
adviceLabel.text = "正常範圍"
} else if changeBMI <= 27 {
adviceLabel.text = "過重"
} else if changeBMI <= 30 {
adviceLabel.text = "輕度肥胖"
} else if changeBMI <= 35 {
adviceLabel.text = "中度肥胖"
} else if changeBMI >= 35 {
adviceLabel.text = "重度肥胖"
}
view.endEditing(true)
}
}
|
fea4ba036d20cec8fdaae6a3c70baadc83d3f0c3
|
[
"Swift"
] | 1
|
Swift
|
Timmy-LUO/BMITest
|
1441df184cddd760c7683704b53f085eed92a298
|
c56c23162bc3ac14a499414a767a4514befd12c0
|
refs/heads/master
|
<file_sep>Titanic=data.frame(Titanic)
attach(Titanic)
head(Titanic)
table(Titanic$Sex)
table(Titanic$Sex,Titanic$Age)
table(Titanic$Age,Titanic$Survived)
table(Titanic$Age,Titanic$Class)
<file_sep>### Mapping values
### Defining some dictionary
dict<-data.frame(animal=c('pig','cow','salmon'),meat=c('bacon','beef','Nova lox'))
dict
### Creating a new data frame
data<-data.frame(meat=c('bacon', 'beef', 'bacon', 'Nova lox', 'bacon'))
data
### Matching meat with animal
data$animal <- dict[match(data$meat, key$meat), 'animal']
data
<file_sep>### Correlation coefficient
data=data.frame(a=c(1,7,0,5,2),b=c(2,0,2,2,4),c=c(3,-1,4,3,1))
data
cor(data$a,data$b)
cor(data$b,data$a)
cor(data$a,data$c)
cor(data$b,data$c)
cor(data) ### Correlation matrix
<file_sep>x=c(1,2,3,5,6,7,3)
y=c('a','b','c','a','b','c','a')
z=table(x,y)
z
dim(z)
dimnames(z)
dimnames(z)$x ### Renaming rows
dimnames(z)$y ### Renaming columns
dimnames(z)$x <- c('L1','L2','L3','L4','L5','L6')
dimnames(z)$y <- c('aa','bb','cc')
z
<file_sep>### Combining two data frames (column wise)
set.seed(1)
m <- cbind(1, 1:7)
m
m <- cbind(m, 8:14)[, c(1, 2, 3)]
m
d1 <- data.frame(x=1:5, y1=rnorm(5))
d2 <- data.frame(x=2:6, y2=rnorm(5))
d1
d2
cbind(d1,d2)
### Combining two data frames (row wise)
set.seed(1)
m <- rbind(1, 1:7)
m
m <- rbind(m, 8:14)[c(1, 2, 3), ]
m
d3 <- data.frame(x=1:5, y1=rnorm(5))
d4 <- data.frame(x=6:10, y1=rnorm(5))
d3
d4
rbind(d3,d4)
<file_sep>### Reshaping and pivoting
install.packages("reshape")
library(reshape)
set.seed(1)
d1 <- data.frame(id=c(1,2,3,1,2),x=6:10, y=rnorm(5))
d1
d2=t(d1) ### Matrix transpose
d2
d3=melt(d1,id="id") ### Reshaping
d3
id.means <- cast(d3, id~variable, mean) ### Mean function pivot for "id"
id.means
### Converting long and wide format
install.packages('reshape2')
library('reshape2')
attach(USArrests)
head(USArrests)
head(melt(USArrests))
tail(melt(USArrests))
melt_data<- melt(USArrests, id.vars = c("Murder", "Assault"))
head(melt_data)
tail(melt_data)
head(dcast(melt_data, Murder + Assault ~ variable))
### Filtering
attach(mtcars)
### Bracket notation
head(mtcars[,c(2,4)]) ### Columns 2 and 4
head(mtcars[mtcars$mpg>20,]) ### All columns with mpg > 20
head(mtcars[mtcars$mpg>20,c("mpg","hp")]) ### 'mpg' and 'hp' columns mpg > 20
detach()
### Subset function
head(subset(mtcars, , c("mpg", "hp"))) ### All rows with 'mpg' and 'hp' columns
### Filter and select functions
install.packages("dplyr")
library(dplyr)
attach(iris)
head(iris)
head(filter(iris,Sepal.Length>4.5))
head(select(iris, Petal.Width, Species))
### Chaining operation
head(iris %>% filter(Sepal.Length>4.5) %>% select(Petal.Width, Species))
<file_sep>ages=c(20,22,25,27,21,23,37,31,61,45,41,32)
breaks=c(0,18,25,35,60,100)
labels=c('Tenager','Youth','YoungAdult','MiddleAged','Senior')
cat_ages=cut(ages,breaks,labels)
cat_ages
ages
table(cat_ages)
<file_sep>### Creating data frame
fy <- c(2010,2011,2012,2010,2011,2012,2010,2011,2012)
company <- c("Apple","Apple","Apple","Google","Google",
"Google","Microsoft","Microsoft","Microsoft")
revenue <- c(65225,108249,156508,29321,37905,50175,62484,69943,73723)
profit <- c(14013,25922,41733,8505,9737,10737,18760,23150,16978)
companiesData <- data.frame(fy, company, revenue, profit)
companiesData$margin <- (companiesData$profit / companiesData$revenue) * 100
companiesData$margin <- round(companiesData$margin, 1)
companiesData
### Getting summary of each company based on maximum margin
install.packages('plyr')
library(plyr)
highestProfitMargins <- ddply(companiesData, 'company', summarize,
bestMargin = max(margin))
highestProfitMargins ### Columns of company and bestMarging
highestProfitMargins <- ddply(companiesData, 'company', transform,
bestMargin = max(margin))
highestProfitMargins ### All columns
### Applying more than one function
myResults <- ddply(companiesData, 'company', transform,
highestMargin = max(margin), lowestMargin = min(margin))
myResults
### Using dplyr to see the highest margin of data
### First creating two columns of max and min of marging
install.packages("dplyr")
library(dplyr)
myresults <- companiesData %>% group_by(company) %>%
mutate(highestMargin = max(margin), lowestMargin = min(margin))
myresults
highestProfitMargins <- companiesData %>% group_by(company) %>%
summarise(bestMargin = max(margin))
highestProfitMargins ### Highest margin of the data
### Grouping by date range
vDates <- as.Date(c("2013-06-01","2013-07-08","2013-09-01","2013-09-15"))
### Sorting based on month
vDates.bymonth <- cut(vDates, breaks = "month")
dfDates <- data.frame(vDates, vDates.bymonth)
dfDates
<file_sep>install.packages("sqldf")
library(sqldf)
set.seed(1)
d1 <- data.frame(x=7:12, y1=rnorm(6))
d2 <- data.frame(x=4:9, y2=rnorm(6))
d1
d2
sqldf()
d <- sqldf("select * from d1 inner join d2 on d1.x=d2.x")
sqldf()
d
<file_sep>### Descriptive data summarization
x=c(1,3,4,6,2,2,3,5,3,7,2,9)
y=c(2,3,3,5,4,4,8,1,3,6,8,5)
summary(x)
z <- data.frame(x,y)
str(z)
install.packages('psych')
library(psych)
describe(z)
apply(z,2,mean)
apply(z,2,sd)
apply(z,2,median)
### Histogram, box plot and scatter plot
hist(x, main="Histogram of x")
boxplot(x, main="Boxplot of x")
plot(x,y, main="Scatterplot of x vs y")
### Probability Mass Function
plot(density(x))
### Q-Q Plot for two samples
qqplot(x,y,main="Q-Q plot of x and y")
abline(0,1)
### Side-by-Side Boxplot
data_test=data.frame(age=c(45,35,67,23,43,24,32,41,61,25),
gender=c('M','F','F','M','F','M','M','F','F','M'))
boxplot(data_test$age~data_test$gender)
### Cross-Tabs
cat=data.frame(color=c('blue','green','red','blue','red','green','red','blue'),
type=c('a','a','b','c','c','a','c','b'))
table(cat)
### Removing NaN
x=c(1,3,4,6,2,NaN,3,5,3,7,2,9)
y=c(2,3,3,5,4,4,8,1,3,NaN,8,5)
data <- cbind(x,y)
data
data[complete.cases(data),]
### Replacing NaN with mean
x=c(1,3,4,6,2,NaN,3,5,3,7,2,9)
y=c(2,3,3,5,4,4,8,1,3,NaN,8,5)
data <- cbind(x,y)
means <- colMeans(data, na.rm=TRUE)
means
for (i in 1:ncol(data)){
data[is.na(data[, i]), i] <- means[i]
}
data
### z-score Normalizing
install.packages("clusterSim")
library(clusterSim)
data.Normalization (data,type="n1",normalization="column")
### Min-Max Normalizing
data.Normalization (data,type="n4",normalization="column")
<file_sep>#libraries needed
unloadNamespace("dplyr")
unloadNamespace("randomForest()")
install.packages("dplyr")
library(dplyr)
library(rpart)
library(ggplot2)
install.packages("randomForest")
library(randomForest)
getwd()
setwd("C:/Users/Admin/Documents/DataScience/PracticeProject/TakeHomeChallenges")
#read data from conversion_data.csv
data = read.csv('conversion_data.csv')
head(data)
#structure data in string
str(data)
#summary of data
summary(data)
#investigate abour max age 123
sort(unique(data$age), decreasing=TRUE)
#
subset(data, age>79)
#remove data for age>79 it is unrealistics
data = subset(data, age<80)
head(data)
#sense the data
data_country = data %>%
group_by(country) %>%
summarise(conversion_rate = mean(converted))
data_country
ggplot(data=data_country, aes(x=country, y=conversion_rate))+
geom_bar(stat = "identity", aes(fill = country))
#
data_pages = data %>%
group_by(total_pages_visited) %>%
summarise(conversion_rate = mean(converted))
data_pages
qplot(total_pages_visited, conversion_rate, data=data_pages, geom="line")
# machine learning
data$converted = as.factor(data$converted) # let's make the class a factor
data$new_user = as.factor(data$new_user) #also this a factor
levels(data$country)[levels(data$country)=="Germany"]="DE"
# Shorter name, easier to plot.
train_sample = sample(nrow(data), size = nrow(data)*0.66)
train_data = data[train_sample,]
test_data = data[-train_sample,]
rf = randomForest(y=train_data$converted, x = train_data[, -ncol(train_data)],
ytest = test_data$converted, xtest = test_data[, -ncol(test_data)],
ntree = 100, mtry = 3, keep.forest = TRUE)
rf
#checking variable importance
varImpPlot(rf,type=2)
#
rf = randomForest(y=train_data$converted, x = train_data[, -c(5, ncol(train_data))],
ytest = test_data$converted, xtest = test_data[, -c(5, ncol(train_data))],
ntree = 100, mtry = 3, keep.forest = TRUE, classwt = c(0.7,0.3))
rf
#Re-checking variable importance
varImpPlot(rf,type=2)
#partial dependance plots for variables
op <- par(mfrow=c(2, 2))
partialPlot(rf, train_data, country, 1)
partialPlot(rf, train_data, age, 1)
partialPlot(rf, train_data, new_user, 1)
partialPlot(rf, train_data, source, 1)
#
tree = rpart(data$converted ~ ., data[, -c(5,ncol(data))],
control = rpart.control(maxdepth = 3),
parms = list(prior = c(0.7, 0.3))
)
tree
<file_sep># Data-Science-Projects-in-R--Self
Folder One:
TakeHomeChallenges
This folder contains takehome challenges by boot camp data science.
Currently I have worked on three.
1. Covernsion Rate
2. Employee Retention
3.
Folder Two:
Titanic Sinking
This is online project available on kaggle.com
It predicts survival on titanic sinking
1. Data wragling to find missing values, split values, replace values
2. Data transformation adding new columns, geneder, male female etc
3. Data manipulation and visualisation using ggplot2, mosaic plot
4. Finally predicts titanic survival
<file_sep>### Dummy variables
install.packages("dummy")
library(dummy)
data=data.frame(gender=c('M','F','F','M'),age=c(20,30,40,50))
data
data$gender <- factor(data$gender) ### Creating factors
is.factor(gender_new)
data$gender
### Creating dummies
new_gender=dummy(data, p = "all", object = NULL, int = FALSE, verbose = FALSE)
new_gender
cbind(data,new_gender)
<file_sep>data=data.frame(x=c(1,3,2,4,5,6,4,2,5),y=c(2,4,2,7,4,3,2,1,8))
data
set.seed(1)
#### Half of rows as sample
data_sample=sample(1: nrow(data), 0.5*nrow(data))
data[data_sample,]
<file_sep>z <- c(1,4,5,6,1,2,4,3,8,7)
z[duplicated(z)] ### Finding duplicates in a vector
z[!duplicated(z)] ### Removing duplicates in a vector
d1 <- data.frame(id=c(1,2,3,1,2),x=c(6,7,8,6,7))
d1
d1[duplicated(d1),] ### Finding duplicates in a data frame
d1[!duplicated(d1), ] ### Removing duplicates in a data frame
<file_sep>### Existing local data
mydata1 <- read.csv("C:/Users/Admin/Documents/GitHub/Data-Analysis-Using-R_Self/Data_Wrangling/student-mat.csv",sep=";",header=TRUE)
head(mydata1)
mydata2 <- read.table("C:/Users/Admin/Documents/GitHub/Data-Analysis-Using-R_Self/Data_Wrangling/student-mat.csv",sep=";",header=TRUE)
head(mydata2)
### Help with some external data
install.packages("quantmod")
library(quantmod)
getSymbols("AAPL")
barChart(AAPL)
barChart(AAPL['2015-10-01::2015-10-12'])
### Accessing data from HTML webpage
### Needed package
install.packages("XML")
library(XML)
u <- 'http://finance.yahoo.com/q/op?s=AAPL+Options'
tables = readHTMLTable(u)
names(tables)
tables[[2]] ### Accessing table #2 as an example
### Directly accessing table number 2 as an example
doc = htmlParse(u)
tableNodes = getNodeSet(doc, "//table")
tb = readHTMLTable(tableNodes[[2]])
tb
<file_sep>install.packages('ggplot2')
library(ggplot2)
ggplot(mtcars, aes(x=disp, y=mpg),main='mpg vs.disp') + geom_line() + geom_point()
ggplot(mtcars, aes(factor(cyl))) + geom_bar()
par(mfrow=c(1,2))
boxplot(mtcars$disp~mtcars$cyl,main='Boxplot of disp and cyl')
boxplot(mtcars$mpg~mtcars$cyl,main='Boxplot of mpg and cyl')
<file_sep>### Adding new column
### By equation
fy <- c(2010,2011,2012,2010,2011,2012,2010,2011,2012)
company <- c("Apple","Apple","Apple","Google","Google",
"Google","Microsoft","Microsoft","Microsoft")
revenue <- c(65225,108249,156508,29321,37905,50175,62484,69943,73723)
profit <- c(14013,25922,41733,8505,9737,10737,18760,23150,16978)
companiesData <- data.frame(fy, company, revenue, profit)
companiesData$margin <- (companiesData$profit / companiesData$revenue) * 100
companiesData$margin <- round(companiesData$margin, 1)
companiesData
### By R's transform
companiesData <- transform(companiesData,
margin = round((profit/revenue) * 100, 1))
companiesData
### By apply() function
companiesData$margin <- apply(companiesData[,c('revenue', 'profit')], 1,
function(x) { (x[2]/x[1]) * 100 } )
companiesData
### By mapply() function
companiesData$margin <- mapply(function(x, y) round((x/y) * 100, 1),
companiesData$profit, companiesData$revenue)
companiesData
### Using 'dplyr' package
library(dplyr)
companiesData <- mutate(companiesData, margin = round((profit/revenue) * 100, 1))
companiesData
<file_sep>### Detecting outliers
### First replace missing values with zero
data <- data.frame(x=c(.1,.2,NaN,-20,.8,.9,.5,.1,1),y=c(2,NaN,.5,20,1,.3,.1,.8,.9))
data
for(i in 1:ncol(data)){
data[is.na(data[,i]), i] <- 0
}
data
### Detecting, filtering outliers and replacing with mean of column
for(j in 1:ncol(data)){
for (i in 1:nrow(data)){
if ((data[i,j] < (mean(data[[j]])-(1.5)*sd(data[[j]]))|
(data[i,j] > (mean(data[[j]])+1.5*sd(data[[j]])))))
{data[i,j]<-mean(data[[j]])}
}
}
data
<file_sep>### Binning (equal length bins)
x=c(1,2,3,4,2,4,7,8,12,5,6,8)
y=cut(x,4)
y
k=split(x,y)
k
y=factor(y)
aggregate(x,by=list(y),FUN='mean')
aggregate(x,by=list(y),FUN='sd')
### Binning (equal number of datapoints in each interval)
breaks=quantile(x,probs=c(0,.25,.5,.75,1))
breaks
z=cut(x,breaks,include.lowest=TRUE)
z
<file_sep>### Sorting
library(dplyr)
library(plyr)
attach(mtcars)
### Using order function
mtcars_Ordered <- order(mtcars$mpg)
mtcars_Ordered ### This is just the order of rows
mtcars_ordered <- mtcars[mtcars_Ordered,] ### mpg ordered mtcars
head(mtcars_ordered)
### Descending order
mtcars_ordered <- mtcars[order(-mtcars$mpg),]
head(mtcars_ordered)
### Sorting more than one column
mtcars_ordered <- mtcars[order(mtcars$mpg,-mtcars$cyl),]
head(mtcars_ordered)
### or
mtcars_ordered <- mtcars[with(mtcars,order(mpg,-cyl)),]
head(mtcars_ordered)
### Using doBy package
install.packages('doBy')
library(doBy)
mtcars_ordered <- orderBy(~mpg-cyl,data=mtcars)
head(mtcars_ordered)
### Using arrange function
mtcars_ordered <- arrange(mtcars, mpg, desc(cyl))
head(mtcars_ordered)
<file_sep>### Replacing missing values with zero
data <- data.frame(x=c(1,2,NaN,5),y=c(4,NaN,3,7))
data
for(i in 1:ncol(data)){
data[is.na(data[,i]), i] <- 0
}
data
for(j in 1:ncol(data)){
for (i in 1:nrow(data)){
if ((data[i,j] < 0.5*mean(data[[j]]))|(data[i,j] > 2*mean(data[[j]])))
{data[i,j]<-mean(data[[j]])}
}
}
data
<file_sep>x <- data.frame(k1 = c(1,NA,3,4,5), k2 = c(1,NA,NA,4,5), k3 = 8:12)
y <- data.frame(k1 = c(NA,2,NA,4,5), k2 = c(NA,NA,3,4,5), k3 = 14:18)
x
y
merge(x,y,all=FALSE) ### Inner join
merge(x,y,all.x=TRUE) ### Left join
merge(x,y,all.y=TRUE) ### Right join
merge(x,y,all=TRUE) ### Outer join
<file_sep>#library("RODBC")
install.packages("RCurl")
install.packages("bitops")
install.packages("rjson")
library("RCurl")
library("rjson")
#library(rClr)
#library("RSQLServer")
#library("checkpoint")
Titanic_DS <- read.csv("C:\\Users\\Admin\\Documents\\DataScience\\test.csv")
Titanic_DS$PassengerId <- NULL
Titanic_DS$Name <- NULL
Titanic_DS$Cabin <- NULL
Titanic_DS$Ticket <- NULL
i <- 1
#Titanic_DS <- Titanic_DS[1:75, ]
mm <- matrix(0, ncol = 9)
mm <- data.frame(mm)
mm <- mm[-1,]
while( i <= nrow(Titanic_DS) ){
Titanic_DS <- na.omit(Titanic_DS)
# Accept SSL certificates issued by public Certificate Authorities
options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")))
h = basicTextGatherer()
hdr = basicHeaderGatherer()
Titanic_DS_Final <- Titanic_DS[i,]
req = list(
Inputs = list(
"input1" = list(
"ColumnNames" = list("PassengerClass", "Gender", "Age", "SiblingSpouse", "ParentChild", "FarePrice", "PortEmbarkation"),
"Values" = list( list(Titanic_DS_Final$Pclass, Titanic_DS_Final$Sex, Titanic_DS_Final$Age, Titanic_DS_Final$SibSp, Titanic_DS_Final$Parch, Titanic_DS_Final$Fare, Titanic_DS_Final$Embarked) )
) ),
GlobalParameters = setNames(fromJSON('{}'), character(0))
)
body = enc2utf8(toJSON(req))
api_key = "<KEY> # Replace this with the API key for the web service
authz_hdr = paste('Bearer', api_key, sep=' ')
h$reset()
curlPerform(url = "https://ussouthcentral.services.azureml.net/workspaces/8fb252a917064ce0965cd059eaa5af55/services/321aa10dcfa2488dab853eaf2d2a13b2/execute?api-version=2.0&details=true",
httpheader=c('Content-Type' = "application/json", 'Authorization' = authz_hdr),
postfields=body,
writefunction = h$update,
headerfunction = hdr$update,
verbose = TRUE
)
headers = hdr$value()
httpStatus = headers["status"]
if (httpStatus >= 400)
{
print(paste("The request failed with status code:", httpStatus, sep=" "))
# Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
print(headers)
}
print("Result:")
result = h$value()
finalResult <- fromJSON(result)
colNames <- finalResult$Results$output1$value$ColumnNames
c <- unlist(finalResult$Results$output1$value$Values)
mm[nrow(mm)+1,] <- rbind(c[1], c[2], c[3], c[4], c[5], c[6], c[7], c[8], c[9])
i <- i + 1
}
mm$ScoredProbabilities <- as.numeric(format(round(as.numeric(mm$X9) * 100, 2), nsmall = 2))
mm$ScoredProbabilitiess <- paste(as.character(mm$ScoredProbabilities), "%")
mm$X9 <- NULL
library(data.table)
setnames(mm, old = c('X1','X2','X3','X4','X5','X6','X7','X8'), new = c(colNames[1], colNames[2], colNames[3], colNames[4], colNames[5], colNames[6], colNames[7], colNames[8]))
write.csv(s, "C:\\Users\\Admin\\Documents\\DataScience\\QQQ", row.names=TRUE)
pp <- read.csv("C:\\Users\\Admin\\Documents\\DataScience\\QQQ.csv")
pp
<file_sep>### Mapping missing values of data frame with values of another data frame
### having same index
x <- data.frame(x1=c(NaN,2.5,NaN,3.5,4.5,NaN))
y <- data.frame(y1=c(1,2,3,4,5,6))
x
y
### Replacing missing values of x1 column with y1 column
for (i in 1:nrow(x)) {
if (is.na(x[i,1])){
x[i,1] <- y[i,1]
}}
x
|
fa952113cd3e481daab36fbc40112deaeddbdcd3
|
[
"Markdown",
"R"
] | 25
|
R
|
vaishalilambe/Data-Analysis-Using-R_Self
|
ffb2b3764aa2f545b5547a82e04bae8a54bb7ae3
|
ae2b991fde7016bc3ef78e20adfa2af346ea26b0
|
refs/heads/master
|
<file_sep>package com.runningsnail.base.mvp;
/**
* @author yongjie created on 2019-07-22.
*/
public interface BaseModel {
}
<file_sep>package com.runningsnail.base.utils;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.List;
public class PermissionUtil {
/**
* 是否需要检查权限
*/
private static boolean needCheckPermission() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
}
/**
* 获取sd存储卡读写权限
*
* @return 是否已经获取权限,没有自动申请
*/
public static boolean getExternalStoragePermissions(@NonNull Activity activity, int requestCode) {
return requestPermissions(activity, requestCode, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
/**
* 获取拍照权限
*
* @return 是否已经获取权限,没有自动申请
*/
public static boolean getCameraPermissions(@NonNull Activity activity, int requestCode) {
return requestPermissions(activity, requestCode, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
/**
* 获取麦克风权限
*
* @return 是否已经获取权限,没有自动申请
*/
public static boolean getAudioPermissions(@NonNull Activity activity, int requestCode) {
return requestPermissions(activity, requestCode, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
/**
* 获取定位权限
*
* @return 是否已经获取权限,没有自动申请
*/
public static boolean getLocationPermissions(@NonNull Activity activity, int requestCode) {
return requestPermissions(activity, requestCode, Manifest.permission.ACCESS_COARSE_LOCATION);
}
/**
* 获取读取联系人权限
*
* @return 是否已经获取权限,没有自动申请
*/
public static boolean getContactsPermissions(@NonNull Activity activity, int requestCode) {
return requestPermissions(activity, requestCode, Manifest.permission.READ_CONTACTS);
}
/**
* 获取发送短信权限
*
* @return 是否已经获取权限,没有自动申请
*/
public static boolean getSendSMSPermissions(@NonNull Activity activity, int requestCode) {
return requestPermissions(activity, requestCode, Manifest.permission.SEND_SMS);
}
/**
* 获取拨打电话权限
*
* @return 是否已经获取权限,没有自动申请
*/
public static boolean getCallPhonePermissions(@NonNull Activity activity, int requestCode) {
return requestPermissions(activity, requestCode, Manifest.permission.CALL_PHONE);
}
public static List<String> getDeniedPermissions(@NonNull Activity activity, @NonNull String... permissions) {
if (!needCheckPermission()) {
return null;
}
List<String> deniedPermissions = new ArrayList<>();
for (String permission : permissions) {
if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
deniedPermissions.add(permission);
}
}
if (!deniedPermissions.isEmpty()) {
return deniedPermissions;
}
return null;
}
/**
* 是否拥有权限
*/
public static boolean hasPermissions(@NonNull Activity activity, @NonNull String... permissions) {
if (!needCheckPermission()) {
return true;
}
for (String permission : permissions) {
if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
/**
* 是否拒绝了再次申请权限的请求(点击了不再询问)
*/
public static boolean deniedRequestPermissionsAgain(@NonNull Activity activity, @NonNull String... permissions) {
if (!needCheckPermission()) {
return false;
}
List<String> deniedPermissions = getDeniedPermissions(activity, permissions);
for (String permission : deniedPermissions) {
if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_DENIED) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
//当用户之前已经请求过该权限并且拒绝了授权这个方法返回true
return true;
}
}
}
return false;
}
/**
* 打开app详细设置界面<br/>
* <p>
* 在 onActivityResult() 中没有必要对 resultCode 进行判断,因为用户只能通过返回键才能回到我们的 App 中,<br/>
* 所以 resultCode 总是为 RESULT_CANCEL,所以不能根据返回码进行判断。<br/>
* 在 onActivityResult() 中还需要对权限进行判断,因为用户有可能没有授权就返回了!<br/>
*/
public static void startApplicationDetailsSettings(@NonNull Activity activity, int requestCode) {
Toast.makeText(activity, "点击权限,并打开全部权限", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
intent.setData(uri);
activity.startActivityForResult(intent, requestCode);
}
/**
* 申请权限<br/>
* 使用onRequestPermissionsResult方法,实现回调结果或者自己普通处理
*
* @return 是否已经获取权限
*/
public static boolean requestPermissions(Activity activity, int requestCode, String... permissions) {
if (!needCheckPermission()) {
return true;
}
if (!hasPermissions(activity, permissions)) {
if (deniedRequestPermissionsAgain(activity, permissions)) {
startApplicationDetailsSettings(activity, requestCode);
//返回结果onActivityResult
} else {
List<String> deniedPermissions = getDeniedPermissions(activity, permissions);
if (deniedPermissions != null) {
ActivityCompat.requestPermissions(activity, deniedPermissions.toArray(new String[deniedPermissions.size()]), requestCode);
//返回结果onRequestPermissionsResult
}
}
return false;
}
return true;
}
/**
* 申请权限返回方法
*/
public static void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults, @NonNull OnRequestPermissionsResultCallbacks callBack) {
// Make a collection of granted and denied permissions from the request.
List<String> granted = new ArrayList<>();
List<String> denied = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
String perm = permissions[i];
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
granted.add(perm);
} else {
denied.add(perm);
}
}
if (null != callBack) {
if (!granted.isEmpty()) {
callBack.onPermissionsGranted(requestCode, granted, denied.isEmpty());
}
if (!denied.isEmpty()) {
callBack.onPermissionsDenied(requestCode, denied, granted.isEmpty());
}
}
}
/**
* 申请权限返回
*/
public interface OnRequestPermissionsResultCallbacks {
/**
* @param isAllGranted 是否全部同意
*/
void onPermissionsGranted(int requestCode, List<String> perms, boolean isAllGranted);
/**
* @param isAllDenied 是否全部拒绝
*/
void onPermissionsDenied(int requestCode, List<String> perms, boolean isAllDenied);
}
}
<file_sep>ext {
android = [
compileSdkVersion : 28,
buildToolsVersion : "28.0.3",
minSdkVersion : 19,
targetSdkVersion : 28,
versionCode : 1,
versionName : "1.0",
testInstrumentationRunner: "android.support.test.runner.AndroidJUnitRunner"
]
dependVersion = [
refrofit2: "2.6.2"
]
dependencies = [
//androidX
"androidx_material" : 'com.google.android.material:material:1.0.0',
"androidx_cardView" : 'androidx.cardview:cardview:1.0.0',
"androidx_appcompat" : 'androidx.appcompat:appcompat:1.1.0',
"androidx_constraintLayout": 'androidx.constraintlayout:constraintlayout:1.1.3',
//google多dex解决方案
"androidx_multiDex" : 'androidx.multidex:multidex:2.0.0',
"androidx_recyclerView" : 'androidx.recyclerview:recyclerview:1.0.0',
"androidx_support_v4" : 'androidx.legacy:legacy-support-v4:1.0.0',
//google官方的运行时权限申请框架支持Androidx 不用这个了
"request_permission" : 'pub.devrel:easypermissions:3.0.0',
//第三方运行时权限处理框架
"permissionsDispatcher" : 'org.permissionsdispatcher:permissionsdispatcher:4.6.0',
"permissionsDispatcherAnnotationProcessor" : 'org.permissionsdispatcher:permissionsdispatcher-processor:4.6.0',
"kotlinReflect" : 'org.jetbrains.kotlin:kotlin-reflect:1.3.60',
//测试框架
"junit" : 'junit:junit:4.12',
"runner" : 'com.android.support.test:runner:1.0.2',
"espresso_core" : 'com.android.support.test.espresso:espresso-core:3.0.2',
//异步任务
"RxJava3" : 'implementation io.reactivex.rxjava3:rxjava:3.0.0-RC4',
//RxJava3在Android中线程切换
"RxAndroid3" : 'implementation io.reactivex.rxjava3:rxandroid:3.0.0-SNAPSHOT',
//RxJava3生命周期管理
"RxLifecycle3_Android" : 'com.trello.rxlifecycle2:rxlifecycle-android:3.1.0',
//Okhttp3网络请求库的上层封装
"Retrofit2" : 'com.squareup.retrofit2:retrofit:${dependVersion.refrofit2}',
"Retrofit2ConvertGson" : 'com.squareup.retrofit2:converter-gson:${dependVersion.refrofit2}',
"Retrofit2AdapterRxJava2" : 'com.squareup.retrofit2:adapter-rxjava2:${dependVersion.refrofit2}',
//网络请求库
"OkHttp3" : 'com.squareup.okhttp3:okhttp:4.2.2',
"OkHttp3LoggingInterceptor": 'com.squareup.okhttp3:logging-interceptor:4.2.1',
//json和实体的相互转换以及序列化与反序列化
"Gson" : 'com.google.code.gson:gson:2.8.6',
]
}<file_sep>package com.runningsnail.miweather;
import android.content.Context;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.runningsnail.miweather.entity.LocationOption;
import com.runningsnail.miweather.entity.MiLocation;
import com.runningsnail.miweather.utils.EntityConvertHelper;
/**
* 定位帮助类,简单的包装了一个百度定位sdk,用于定位功能
* @author yongjie created on 2019-11-16.
*/
public class LocationWrapper {
private LocationClient locationClient;
private LocationClientOption locationClientOption;
public LocationWrapper(Context context) {
locationClient = new LocationClient(context.getApplicationContext());
locationClientOption = new LocationClientOption();
locationClientOption.setIsNeedAddress(true);
locationClientOption.setCoorType(LocationOption.CoorType.GCJ02.coorType);
locationClient.setLocOption(locationClientOption);
}
public LocationWrapper(Context context, LocationOption locationOption) {
locationClient = new LocationClient(context.getApplicationContext());
locationClientOption = new LocationClientOption();
setOption(locationOption);
}
public void setLocationOption(LocationOption locationOption) {
setOption(locationOption);
}
/**
* start调用之后会返回一次定位信息
*/
public void start() {
locationClient.start();
}
/**
* 停止定位信息,重新获取定位信息使用 {@link #start()}
*/
public void stop() {
locationClient.stop();
}
/**
* 重新启动定位服务
*/
public void restart() {
locationClient.restart();
}
/**
* 主动请求获取位置信息
*/
public void requestLocation() {
locationClient.requestLocation();
}
public void registerLocationCallback(LocationListener LocationListener) {
locationClient.registerLocationListener(LocationListener);
}
public void unregisterLocationCallback(LocationListener LocationListener) {
locationClient.unRegisterLocationListener(LocationListener);
}
private void setOption(LocationOption locationOption) {
locationClientOption.setIsNeedAddress(locationOption.isNeedAddress());
locationClientOption.setCoorType(locationOption.getCoorType().coorType);
locationClientOption.setIsNeedAltitude(locationOption.isNeedAltitude());
locationClient.setLocOption(locationClientOption);
}
public static abstract class LocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation bdLocation) {
MiLocation miLocation = EntityConvertHelper.convertBDLocationTo(bdLocation);
onReceiveLocation(miLocation);
}
public abstract void onReceiveLocation(MiLocation miLocation);
}
}
<file_sep>package com.runningsnail.base.utils;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
public class AppUtils {
public static void hiddenStatusBar(Activity activity) {
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
public static void showStatusBar(Activity activity) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
public static void hiddenNavagationBar(Activity activity) {
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
View decorView = window.getDecorView();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
int visibility = decorView.getSystemUiVisibility();
decorView.setSystemUiVisibility(visibility & ~View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
public static void showNavagationBar(Activity activity) {
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
public static void setStatusBarColor(int color) {
}
public static void setStatusBarColor(Color color) {
}
public static void setNavagationBarColor(int color) {
}
public static void setNavagationBarColor(Color color) {
}
}
<file_sep>apply plugin: 'com.android.library'
android {
compileSdkVersion rootProject.ext.android.compileSdkVersion
defaultConfig {
minSdkVersion rootProject.ext.android.minSdkVersion
targetSdkVersion rootProject.ext.android.targetSdkVersion
versionCode rootProject.ext.android.versionCode
versionName rootProject.ext.android.versionName
testInstrumentationRunner rootProject.ext.android.testInstrumentationRunner
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation rootProject.ext.dependencies.androidx_support_v4
testImplementation rootProject.ext.dependencies.junit
androidTestImplementation rootProject.ext.dependencies.runner
androidTestImplementation rootProject.ext.dependencies.espresso_core
}
<file_sep>package com.runningsnail.base.utils;
import android.os.Looper;
public class ThreadUtil {
/**
* 判断是否是主线程
*/
public static boolean isMainThread() {
return Thread.currentThread() == Looper.getMainLooper().getThread();
}
}
<file_sep>package com.runningsnail.base.utils;
import java.lang.reflect.Method;
/**
* 通过反射的方式设置/取得系统属性
*/
public class SystemPropertiesUtils {
public static boolean getBoolean(String key, boolean def) {
try {
Class<?> clazz = Class.forName("android.os.SystemProperties");
Method method = clazz.getDeclaredMethod("getBoolean", String.class, boolean.class);
method.setAccessible(true);
Boolean result = (Boolean) method.invoke(null, key, def);
return result;
} catch (Exception e) {
return def;
}
}
public static String get(String key, String def){
try {
Class<?> clazz = Class.forName("android.os.SystemProperties");
Method method = clazz.getDeclaredMethod("get", String.class, String.class);
method.setAccessible(true);
String result = (String) method.invoke(null, key, def);
return result;
} catch (Exception e) {
return def;
}
}
}
<file_sep># MiWeather
一个高仿小米天气的App
# 应用架构
Android Jetpack
# 用到的三方开源库
<file_sep>package com.runningsnail.base.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FileUtils {
private FileUtils() {
throw new UnsupportedOperationException("工具类不建议创建对象");
}
/**
* 根据文件路径获取文件
*
* @param filePath 文件路径
* @return 文件
*/
public static File getFileByPath(String filePath) {
return HiStringUtils.isSpace(filePath) ? null : new File(filePath);
}
/**
* 判断文件是否存在
*
* @param filePath 文件路径
*/
public static boolean isFileExists(String filePath) {
return isFileExists(getFileByPath(filePath));
}
/**
* 判断文件是否存在
*
* @param file 文件
*/
public static boolean isFileExists(File file) {
return file != null && file.exists();
}
/**
* 判断是否是目录
*
* @param dirPath 目录路径
*/
public static boolean isDir(String dirPath) {
return isDir(getFileByPath(dirPath));
}
/**
* 判断是否是目录
*
* @param file 文件
*/
public static boolean isDir(File file) {
return isFileExists(file) && file.isDirectory();
}
/**
* 判断是否是文件
*
* @param filePath 文件路径
*/
public static boolean isFile(String filePath) {
return isFile(getFileByPath(filePath));
}
/**
* 判断是否是文件
*
* @param file 文件
*/
public static boolean isFile(File file) {
return isFileExists(file) && file.isFile();
}
/**
* 判断目录是否存在,不存在则判断是否创建成功
*
* @param dirPath 文件路径
*/
public static boolean createOrExistsDir(String dirPath) {
return createOrExistsDir(getFileByPath(dirPath));
}
/**
* 判断目录是否存在,不存在则判断是否创建成功
*
* @param file 文件
*/
public static boolean createOrExistsDir(File file) {
return file != null && (file.exists() ? file.isDirectory() : file.mkdirs());
}
/**
* 判断文件是否存在,不存在则判断是否创建成功
*
* @param filePath 文件路径
* @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败
*/
public static boolean createOrExistsFile(String filePath) {
return createOrExistsFile(getFileByPath(filePath));
}
/**
* 判断文件是否存在,不存在则判断是否创建成功
*
* @param file 文件
* @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败
*/
public static boolean createOrExistsFile(File file) {
if (file == null) {
return false;
}
// 如果存在,是文件则返回true,是目录则返回false
if (file.exists()) {
return file.isFile();
}
if (!createOrExistsDir(file.getParentFile())) {
return false;
}
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 删除目录
*
* @param dirPath 目录路径
* @return {@code true}: 删除成功<br>{@code false}: 删除失败
*/
public static boolean deleteDir(String dirPath) {
return deleteDir(getFileByPath(dirPath));
}
/**
* 删除目录
*
* @param dir 目录
* @return {@code true}: 删除成功<br>{@code false}: 删除失败
*/
public static boolean deleteDir(File dir) {
if (dir == null) {
return false;
}
// 目录不存在返回true
if (!dir.exists()) {
return true;
}
// 不是目录返回false
if (!dir.isDirectory()) {
return false;
}
// 现在文件存在且是文件夹
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (file.isFile()) {
if (!deleteFile(file)) {
return false;
}
} else if (file.isDirectory()) {
if (!deleteDir(file)) {
return false;
}
}
}
}
return dir.delete();
}
/**
* 删除文件
*
* @param srcFilePath 文件路径
* @return {@code true}: 删除成功<br>{@code false}: 删除失败
*/
public static boolean deleteFile(String srcFilePath) {
return deleteFile(getFileByPath(srcFilePath));
}
/**
* 删除文件
*
* @param file 文件
* @return {@code true}: 删除成功<br>{@code false}: 删除失败
*/
public static boolean deleteFile(File file) {
return file != null && (!file.exists() || file.isFile() && file.delete());
}
/**
* 删除目录下的所有文件
*
* @param dirPath 目录路径
* @return {@code true}: 删除成功<br>{@code false}: 删除失败
*/
public static boolean deleteFilesInDir(String dirPath) {
return deleteFilesInDir(getFileByPath(dirPath));
}
/**
* 删除目录下的所有文件
*
* @param dir 目录
* @return {@code true}: 删除成功<br>{@code false}: 删除失败
*/
public static boolean deleteFilesInDir(File dir) {
if (dir == null) {
return false;
}
// 目录不存在返回true
if (!dir.exists()) {
return true;
}
// 不是目录返回false
if (!dir.isDirectory()) {
return false;
}
// 现在文件存在且是文件夹
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (file.isFile()) {
if (!deleteFile(file)) {
return false;
}
} else if (file.isDirectory()) {
if (!deleteDir(file)) {
return false;
}
}
}
}
return true;
}
/**
* 获取目录下所有文件
*
* @param dirPath 目录路径
* @param isRecursive 是否递归进子目录
* @return 文件链表
*/
public static List<File> listFilesInDir(String dirPath, boolean isRecursive) {
return listFilesInDir(getFileByPath(dirPath), isRecursive);
}
/**
* 获取目录下所有文件
*
* @param dir 目录
* @param isRecursive 是否递归进子目录
* @return 文件链表
*/
public static List<File> listFilesInDir(File dir, boolean isRecursive) {
if (isRecursive) return listFilesInDir(dir);
if (dir == null || !isDir(dir)) return null;
List<File> list = new ArrayList<>();
Collections.addAll(list, dir.listFiles());
return list;
}
/**
* 获取目录下所有文件包括子目录
*
* @param dirPath 目录路径
* @return 文件链表
*/
public static List<File> listFilesInDir(String dirPath) {
return listFilesInDir(getFileByPath(dirPath));
}
/**
* 获取目录下所有文件包括子目录
*
* @param dir 目录
* @return 文件链表
*/
public static List<File> listFilesInDir(File dir) {
if (dir == null || !isDir(dir)) return null;
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
list.add(file);
if (file.isDirectory()) {
list.addAll(listFilesInDir(file));
}
}
}
return list;
}
/**
* 获取目录下所有后缀名为suffix的文件
* <p>大小写忽略</p>
*
* @param dirPath 目录路径
* @param suffix 后缀名
* @param isRecursive 是否递归进子目录
* @return 文件链表
*/
public static List<File> listFilesInDirWithFilter(String dirPath, String suffix, boolean isRecursive) {
return listFilesInDirWithFilter(getFileByPath(dirPath), suffix, isRecursive);
}
/**
* 获取目录下所有后缀名为suffix的文件
* <p>大小写忽略</p>
*
* @param dir 目录
* @param suffix 后缀名
* @param isRecursive 是否递归进子目录
* @return 文件链表
*/
public static List<File> listFilesInDirWithFilter(File dir, String suffix, boolean isRecursive) {
if (isRecursive) {
return listFilesInDirWithFilter(dir, suffix);
}
if (dir == null || !isDir(dir)) {
return null;
}
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (file.getName().toUpperCase().endsWith(suffix.toUpperCase())) {
list.add(file);
}
}
}
return list;
}
/**
* 获取目录下所有后缀名为suffix的文件包括子目录
* <p>大小写忽略</p>
*
* @param dirPath 目录路径
* @param suffix 后缀名
* @return 文件链表
*/
public static List<File> listFilesInDirWithFilter(String dirPath, String suffix) {
return listFilesInDirWithFilter(getFileByPath(dirPath), suffix);
}
/**
* 获取目录下所有后缀名为suffix的文件包括子目录
* <p>大小写忽略</p>
*
* @param dir 目录
* @param suffix 后缀名
* @return 文件链表
*/
public static List<File> listFilesInDirWithFilter(File dir, String suffix) {
if (dir == null || !isDir(dir)) {
return null;
}
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (file.getName().toUpperCase().endsWith(suffix.toUpperCase())) {
list.add(file);
}
if (file.isDirectory()) {
list.addAll(listFilesInDirWithFilter(file, suffix));
}
}
}
return list;
}
/**
* 获取目录下所有符合filter的文件
*
* @param dirPath 目录路径
* @param filter 过滤器
* @param isRecursive 是否递归进子目录
* @return 文件链表
*/
public static List<File> listFilesInDirWithFilter(String dirPath, FilenameFilter filter, boolean isRecursive) {
return listFilesInDirWithFilter(getFileByPath(dirPath), filter, isRecursive);
}
/**
* 获取目录下所有符合filter的文件
*
* @param dir 目录
* @param filter 过滤器
* @param isRecursive 是否递归进子目录
* @return 文件链表
*/
public static List<File> listFilesInDirWithFilter(File dir, FilenameFilter filter, boolean isRecursive) {
if (isRecursive) {
return listFilesInDirWithFilter(dir, filter);
}
if (dir == null || !isDir(dir)) {
return null;
}
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (filter.accept(file.getParentFile(), file.getName())) {
list.add(file);
}
}
}
return list;
}
/**
* 获取目录下所有符合filter的文件包括子目录
*
* @param dirPath 目录路径
* @param filter 过滤器
* @return 文件链表
*/
public static List<File> listFilesInDirWithFilter(String dirPath, FilenameFilter filter) {
return listFilesInDirWithFilter(getFileByPath(dirPath), filter);
}
/**
* 获取目录下所有符合filter的文件包括子目录
*
* @param dir 目录
* @param filter 过滤器
* @return 文件链表
*/
public static List<File> listFilesInDirWithFilter(File dir, FilenameFilter filter) {
if (dir == null || !isDir(dir)) {
return null;
}
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (filter.accept(file.getParentFile(), file.getName())) {
list.add(file);
}
if (file.isDirectory()) {
list.addAll(listFilesInDirWithFilter(file, filter));
}
}
}
return list;
}
/**
* 获取目录下指定文件名的文件包括子目录
* <p>大小写忽略</p>
*
* @param dirPath 目录路径
* @param fileName 文件名
* @return 文件链表
*/
public static List<File> searchFileInDir(String dirPath, String fileName) {
return searchFileInDir(getFileByPath(dirPath), fileName);
}
/**
* 获取目录下指定文件名的文件包括子目录
* <p>大小写忽略</p>
*
* @param dir 目录
* @param fileName 文件名
* @return 文件链表
*/
public static List<File> searchFileInDir(File dir, String fileName) {
if (dir == null || !isDir(dir)) {
return null;
}
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (file.getName().toUpperCase().equals(fileName.toUpperCase())) {
list.add(file);
}
if (file.isDirectory()) {
list.addAll(searchFileInDir(file, fileName));
}
}
}
return list;
}
/**
* 获取文件行数
*
* @param filePath 文件路径
* @return 返回文件行数否则返回-1
*/
public static int getFileLines(String filePath) {
return getFileLines(getFileByPath(filePath));
}
/**
* 获取文件行数
*
* @param file 文件
* @return 返回文件行数否则返回-1
*/
public static int getFileLines(File file) {
BufferedReader reader = null;
int count = 1;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while (reader.readLine() != null) {
count++;
}
return count;
} catch (Exception e) {
return -1;
} finally {
CloseUtils.closeIO(reader);
}
}
/**
* 获取文件大小
*
* @param filePath 文件路径
* @return 文件大小否则返回-1
*/
public static long getFileSize(String filePath) {
return getFileSize(new File(filePath));
}
/**
* 获取文件大小,不包括目录
*
* @return 文件大小否则返回-1
*/
public static long getFileSize(File file) {
if (file != null && file.exists() && file.isFile()) {
return file.length();
}
return -1L;
}
/**
* 获取全路径中的最长目录
*
* @param file 文件
* @return filePath最长目录否则返回“”
*/
public static String getDirName(File file) {
if (file == null) {
return "";
}
return getDirName(file.getPath());
}
/**
* 获取全路径中的最长目录
* 比如:
* 路径:/hello/world/hi.txt 返回就是 /hello/world/
*
* @param filePath 文件路径
* @return filePath最长目录否则返回“”
*/
public static String getDirName(String filePath) {
if (HiStringUtils.isSpace(filePath)) {
return "";
}
int lastSep = filePath.lastIndexOf(File.separator);
return lastSep == -1 ? "" : filePath.substring(0, lastSep + 1);
}
/**
* 获取全路径中的文件名
*
* @param file 文件
* @return 返回文件名或者是""
*/
public static String getFileName(File file) {
if (file == null) {
return "";
}
return getFileName(file.getPath());
}
/**
* 获取全路径中的文件名
*
* @param filePath 文件路径
* @return 返回文件名或者是""
*/
public static String getFileName(String filePath) {
if (HiStringUtils.isSpace(filePath)) {
return "";
}
int lastSep = filePath.lastIndexOf(File.separator);
return lastSep == -1 ? "" : filePath.substring(lastSep + 1);
}
/**
* 获取全路径中的不带拓展名的文件名
*
* @param file 文件
* @return 返回不带拓展名的文件名否则返回""
*/
public static String getFileNameNoExtension(File file) {
if (file == null) {
return "";
}
return getFileNameNoExtension(file.getPath());
}
/**
* 获取全路径中的不带拓展名的文件名
*
* @param filePath 文件路径
* @return 返回不带拓展名的文件名否则返回""
*/
public static String getFileNameNoExtension(String filePath) {
if (HiStringUtils.isSpace(filePath)) {
return "";
}
int lastPoi = filePath.lastIndexOf('.');
int lastSep = filePath.lastIndexOf(File.separator);
if (lastSep == -1) {
return (lastPoi == -1 ? "" : filePath.substring(0, lastPoi));
}
if (lastPoi == -1 || lastSep > lastPoi) {
return filePath.substring(lastSep + 1);
}
return filePath.substring(lastSep + 1, lastPoi);
}
/**
* 获取全路径中的文件拓展名
*
* @param file 文件
* @return 返回扩展名否则返回""
*/
public static String getFileExtension(File file) {
if (file == null) {
return "";
}
return getFileExtension(file.getPath());
}
/**
* 获取全路径中的文件拓展名
*
* @param filePath 文件路径
* @return 返回扩展名否则返回""
*/
public static String getFileExtension(String filePath) {
if (HiStringUtils.isSpace(filePath)) {
return "";
}
int lastPoi = filePath.lastIndexOf('.');
int lastSep = filePath.lastIndexOf(File.separator);
if (lastPoi == -1 || lastSep >= lastPoi) {
return "";
}
return filePath.substring(lastPoi + 1);
}
/**
* 向指定文件路径写数据
*
* @param bytes 数据内容
* @param desFile 目录文件路径
* @param append 文件存在是否追加写入
* @return true写入成功,否则返回false
*/
public static boolean writeBytesToFile(byte[] bytes, File desFile, boolean append) {
FileOutputStream outputStream = null;
try {
if (desFile != null) {
desFile.getParentFile().mkdir();
outputStream = new FileOutputStream(desFile, append);
outputStream.write(bytes);
outputStream.flush();
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
CloseUtils.closeIO(outputStream);
}
return false;
}
}
<file_sep>apply plugin: 'com.android.application'
android {
//apk签名配置项
signingConfigs {
release {
storeFile file('./snailkey.keystore')
storePassword '<PASSWORD>'
keyPassword '123456'
keyAlias = 'snailkey'
}
}
compileSdkVersion rootProject.ext.android.compileSdkVersion
buildToolsVersion rootProject.ext.android.buildToolsVersion
defaultConfig {
applicationId "com.runningsnail.miweather"
minSdkVersion rootProject.ext.android.minSdkVersion
targetSdkVersion rootProject.ext.android.targetSdkVersion
versionCode rootProject.ext.android.versionCode
versionName rootProject.ext.android.versionName
testInstrumentationRunner rootProject.ext.android.testInstrumentationRunner
//启用多dex解决64K方法数问题
multiDexEnabled true
javaCompileOptions {
annotationProcessorOptions {
includeCompileClasspath = true
arguments = [ moduleName : project.getName() ]
}
}
}
buildTypes {
release {
//应用签名配置项中的release签名
signingConfig signingConfigs.release
buildConfigField 'boolean', 'LOG_ENABLE', 'false'
buildConfigField 'String', 'weatherToken', '"<KEY>"'
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
//应用签名配置项中的release签名
signingConfig signingConfigs.release
buildConfigField 'boolean', 'LOG_ENABLE', 'true'
buildConfigField 'String', 'weatherToken', '"<KEY>"'
minifyEnabled false
// proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
//引入so的支持
sourceSets{
main{
jniLibs.srcDir 'libs'
jni.srcDirs = [] //disable automatic ndk-build
}
}
//解决metadata冲突
packagingOptions {
exclude 'META-INF/metadata.kotlin_module'
exclude 'META-INF/metadata.jvm.kotlin_module'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation rootProject.ext.dependencies.androidx_material
implementation rootProject.ext.dependencies.androidx_support_v4
implementation rootProject.ext.dependencies.androidx_constraintLayout
implementation rootProject.ext.dependencies.androidx_appcompat
implementation rootProject.ext.dependencies.androidx_multiDex
// implementation rootProject.ext.dependencies.request_permission
implementation rootProject.ext.dependencies.permissionsDispatcher
implementation rootProject.ext.dependencies.permissionsDispatcherAnnotationProcessor
implementation rootProject.ext.dependencies.kotlinReflect
testImplementation rootProject.ext.dependencies.junit
androidTestImplementation rootProject.ext.dependencies.runner
androidTestImplementation rootProject.ext.dependencies.espresso_core
// //network
// implementation rootProject.ext.dependencies["Retrofit2"]
// implementation rootProject.ext.dependencies["OkHttp3"]
// implementation rootProject.ext.dependencies["OkHttp3LoggingInterceptor"]
// implementation rootProject.ext.dependencies["Retrofit2AdapterRxJava2"]
// implementation rootProject.ext.dependencies["Retrofit2ConvertGson"]
// //注解框架,解决view的创建和事件处理
// implementation 'com.jakewharton:butterknife:8.8.1'
// annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
// //内存泄漏框架
// debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.1'
// releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.1'
// // Optional, if you use support library fragments:
// debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.1'
// //组件通信
// implementation 'org.greenrobot:eventbus:3.1.1'
// //RxJava
// implementation 'io.reactivex.rxjava2:rxjava:2.2.2'
// implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
// //JSON处理框架
// implementation 'com.google.code.gson:gson:2.8.5'
// // implementation project(':base')
implementation project(':base')
}
<file_sep>package com.runningsnail.miweather.utils;
import com.baidu.location.BDLocation;
import com.runningsnail.miweather.entity.MiLocation;
/**
* @author yongjie created on 2019-11-16.
*/
public class EntityConvertHelper {
public static MiLocation convertBDLocationTo(BDLocation bdLocation) {
MiLocation miLocation = new MiLocation();
if (bdLocation != null) {
miLocation.setLongitude(bdLocation.getLongitude());
miLocation.setAltitude(bdLocation.getAltitude());
miLocation.setLatitude(bdLocation.getLatitude());
miLocation.setCity(bdLocation.getCity());
miLocation.setCountry(bdLocation.getCountry());
miLocation.setProvince(bdLocation.getProvince());
miLocation.setStreet(bdLocation.getStreet());
miLocation.setStreetNumer(bdLocation.getStreetNumber());
miLocation.setDistrict(bdLocation.getDistrict());
miLocation.setAddrStr(bdLocation.getAddrStr());
miLocation.setLocType(bdLocation.getLocType());
}
return miLocation;
}
}
<file_sep>package com.snail.tdd;
public class Main {
}
<file_sep>package com.runningsnail.base.mvp;
/**
* @author yongjie created on 2019-07-22.
*/
public interface BaseView {
void showError(String msg);
}
<file_sep>package com.runningsnail.miweather.activity;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
/**
* @author yongjie created on 2019/3/30.
*/
public abstract class BaseActivity extends AppCompatActivity {
/**
* 子类输出日志使用这个TAG,命名大写
* 只是为了习惯统一
*/
protected String TAG;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buildLogTag();
hideActionBar();
}
/**
* 是否隐藏ActionBar默认隐藏,子类可重写此方法
*/
protected boolean shouldHideActionBar() {
return true;
}
private void hideActionBar() {
if (shouldHideActionBar()) {
ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null) {
supportActionBar.hide();
}
}
}
/**
* 构建Activity的基础Log,用的是子类的类名
*/
protected void buildLogTag() {
TAG = this.getClass().getSimpleName();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
<file_sep>package com.runningsnail.miweather.entity;
/**
* @author yongjie created on 2019-11-16.
*/
public class LocationOption {
public enum CoorType {
/**
* 国测局坐标
*/
GCJ02("GCJ02"),
/**
* 百度经纬度坐标
*/
BD09ll("BD09ll"),
/**
* 百度墨卡托坐标
*/
BD09("BD09"),
/**
* 海外地区定位,无需设置坐标类型,统一返回WGS84类型坐标
*/
WGS84("WGS84");
public String coorType;
CoorType(String coorType) {
this.coorType = coorType;
}
}
/**
* 定位是否需要位置信息
*/
private boolean needAddress = true;
/**
* 定位是否需要海拔高度信息 默认不需要
*/
private boolean needAltitude = false;
/**
* 经纬度坐标的标准默认是国测局坐标
*/
private CoorType coorType = CoorType.GCJ02;
public boolean isNeedAddress() {
return needAddress;
}
public void setNeedAddress(boolean needAddress) {
this.needAddress = needAddress;
}
public CoorType getCoorType() {
return coorType;
}
public void setCoorType(CoorType coorType) {
this.coorType = coorType;
}
public boolean isNeedAltitude() {
return needAltitude;
}
public void setNeedAltitude(boolean needAltitude) {
this.needAltitude = needAltitude;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("LocationOption{");
sb.append("needAddress=").append(needAddress);
sb.append(", needAltitude=").append(needAltitude);
sb.append(", coorType=").append(coorType);
sb.append('}');
return sb.toString();
}
}
<file_sep>package com.runningsnail.base.mvp;
/**
* @author yongjie created on 2019-07-22.
*/
public abstract class BasePresenter<V extends BaseView, M extends BaseModel> {
protected V view;
protected M model;
public BasePresenter() {
model = createModel();
}
protected void attachView(V view) {
this.view = view;
}
protected void detachView() {
this.view = null;
}
protected abstract M createModel();
}
|
3019025165d7688f47eca72c043aab46725b331e
|
[
"Markdown",
"Java",
"Gradle"
] | 17
|
Java
|
kangjunbin0616/MiWeather
|
5a488010ee7b71c51dae31c95ea77d43face9d39
|
f2c86653d25381f4836ea796e78e2c31c7bf6565
|
refs/heads/master
|
<repo_name>345161974/wcc-wepay<file_sep>/uninstall.php
<?php
// if uninstall.php is not called by WordPress, die
if (!defined('WP_UNINSTALL_PLUGIN')) {
die;
}
function delete_wepay_qrcode_page() {
$page_id = -1;
// 设置付款二维码页面
$author_id = 1;
$slug = 'wepay-page';
$title = 'Wepay_Qrcode_Page';
$wepay_page = get_page_by_title( $title );
// 检查该页面是否存在,如果不存在就新建
if ($wepay_page) {
//file_put_contents(WCC_WEPAY_PLUGIN_PATH.'uninstall.txt', "delete_wepay_qrcode_page() $wepay_page->ID():".$wepay_page->ID.PHP_EOL, FILE_APPEND);
// 此处要记录$post_id的值,此值为: www.xxx.com/?page_id=$post_id 未来显示二维码页面
wp_delete_post($wepay_page->ID, true);
}
}
function delete_wepay_order_query_page() {
$page_id = -1;
// 设置付款二维码页面
$author_id = 1;
$slug = 'wepay-page';
$title = 'Wepay_Order_Query_Page';
$wepay_page = get_page_by_title( $title );
// 检查该页面是否存在,如果不存在就新建
if ($wepay_page) {
//file_put_contents(WCC_WEPAY_PLUGIN_PATH.'uninstall.txt', "delete_wepay_order_query_page() $wepay_page->ID():".$wepay_page->ID.PHP_EOL, FILE_APPEND);
// 此处要记录$post_id的值,此值为: www.xxx.com/?page_id=$post_id 未来显示二维码页面
wp_delete_post($wepay_page->ID, true);
}
}
// 删除二维码页面
delete_wepay_qrcode_page();
// 删除订单查询页面
delete_wepay_order_query_page();
// 删除生成二维码页面option
$option_name1 = 'wepay_qrcode_url';
delete_option($option_name1);
// 删除订单查询页面option
$option_name2 = 'wepay_order_query_url';
delete_option($option_name2);
<file_sep>/README.md
# wcc-wepay
woocommerce wepay plugin, woocommerce微信支付插件
### 重要的事情说三遍:
***本项目代码仅供参考学习!***
***本项目代码仅供参考学习!***
***本项目代码仅供参考学习!***
## 使用前请先注意
* 如果PHP版本是5.x版本,请注意lib/WxPay.Api.php文件中public static function notify($config, $callback, &$msg)...方法
> 因为PHP 7.x没有$GLOBALS['HTTP_RAW_POST_DATA']用法,7.x中用file_get_contents('php://input')替换5.x中$GLOBALS['HTTP_RAW_POST_DATA'],请知悉,代码如下:
``` php
/**
*
* 支付结果通用通知
* @param function $callback
* 直接回调函数使用方法: notify(you_function);
* 回调类成员函数方法:notify(array($this, you_function));
* $callback 原型为:function function_name($data){}
*/
public static function notify($config, $callback, &$msg)
{
// PHP 5.x可以开启该注释
/*
if (!isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'WC_Gateway_Wepay_Response.txt', 'FALSE,未收到数据'.date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
# 如果没有数据,直接返回失败
return false;
}
*/
//如果返回成功则验证签名
try {
//获取通知的数据
//$xml = $GLOBALS['HTTP_RAW_POST_DATA']; // PHP 5.x版本用这个
$xml = file_get_contents('php://input'); // PHP 7.x版本用这个
$result = WxPayNotifyResults::Init($config, $xml);
} catch (WxPayException $e){
$msg = $e->errorMessage();
return false;
}
return call_user_func($callback, $result);
}
```
### 插件已支持功能介绍(2019.04.21更新)
* 支持最基本的PC扫码支付(基于PHP 7.x)
* 支付完成自动跳转(微信demo演示并未提供该参数:return_url,需自己实现该功能...支付宝是自带了自动跳转return_url的参数)
* 增加插件的清理工作:uninstall.php
* 浏览器兼容性测试,支持Chrome,Firefox,IE 11
### 插件已支持功能介绍(2018.12.18更新)
* 支持最基本的PC扫码支付
* 支付完成自动跳转(微信demo演示并未提供该参数:return_url,需自己实现该功能...支付宝是自带了自动跳转return_url的参数)
## 运行环境(2018.12.16更新)
> PHP 7.x
> 成功安装WooCommerce的WordPress系统
> WordPress:WordPress 4.9.9
> WooCommerce:3.5.0
> 微信支付SDK:php_sdk_v3.0.9
## 演示使用

## 如何使用
* 设置固定链接格式(由于微信异步回调对回调链接有要求,不可以设置带参数的)

* 安全证书放置于cert目录下即可,插件会去该路径找安全证书

* 上传插件,开启插件

* WooCommerce付款设置启用微信支付

* WooCommerce微信支付设置支付参数


## 上述设置成功,即可使用微信支付了.
<file_sep>/inc/class-wc-gateway-wepay-qrcode-show.php
<?php get_header(); ?>
<div style="margin-left: 10px;color:#ff0000;font-size:30px;font-weight: bolder;">打开微信app扫码支付</div><br/>
<img alt="支付二维码" src="<?php echo WCC_WEPAY_PLUGIN_URL.'inc/' ?>qrcode.php?data=<?php echo urlencode(urldecode($_GET['url']));?>" style="width:150px;height:150px;"/>
<div id="myDiv" style="color:#ff0000;"></div>
<div id="timer">0</div>
<?php
// echo "qrcode-show page.<br />";
// echo "qrcode-show page qrcode_url is:".$_GET['url'].'<br />';
// echo "qrcode-show page out_trade_no is:".$_GET['out_trade_no'].'<br />';
// echo "qrcode-show page return_url is:". urldecode($_GET['return_url']) .'<br />';
// ?>
<script type="text/javascript">
//设置每隔1000毫秒执行一次load() 方法
var myIntval=setInterval(function(){load()}, 3000);
function load(){
document.getElementById("timer").innerHTML=parseInt(document.getElementById("timer").innerHTML)+1;
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
trade_state=xmlhttp.responseText;
if(trade_state=='SUCCESS'){
document.getElementById("myDiv").innerHTML='支付成功';
//alert(transaction_id);
//延迟3000毫秒执行tz() 方法
clearInterval(myIntval);
setTimeout("location.href='<?php echo urldecode($_GET['return_url']); ?>'", 2000);
}else if(trade_state=='REFUND'){
document.getElementById("myDiv").innerHTML='转入退款';
clearInterval(myIntval);
}else if(trade_state=='NOTPAY'){
document.getElementById("myDiv").innerHTML='请扫码支付';
}else if(trade_state=='CLOSED'){
document.getElementById("myDiv").innerHTML='已关闭';
clearInterval(myIntval);
}else if(trade_state=='REVOKED'){
document.getElementById("myDiv").innerHTML='已撤销';
clearInterval(myIntval);
}else if(trade_state=='USERPAYING'){
document.getElementById("myDiv").innerHTML='用户支付中';
}else if(trade_state=='PAYERROR'){
document.getElementById("myDiv").innerHTML='支付失败';
clearInterval(myIntval);
}
}
}
//orderquery.php 文件返回订单状态,通过订单状态确定支付状态
xmlhttp.open("POST","<?php echo get_option( 'wepay_order_query_url' ); ?>",false);
//下面这句话必须有
//把标签/值对添加到要发送的头文件。
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("out_trade_no=<?php echo $_GET['out_trade_no']; ?>");
}
</script>
<?php get_footer(); ?>
<file_sep>/inc/class-wc-gateway-wepay-order-query.php
<?php
/**
*
* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
* 请勿直接直接使用样例对外提供服务
*
**/
ini_set('display_errors',1);
require_once WCC_WEPAY_PLUGIN_PATH."lib/WxPay.Data.php";
require_once WCC_WEPAY_PLUGIN_PATH."lib/WxPay.Api.php";
require_once WCC_WEPAY_PLUGIN_PATH."inc/WxPay.Config.php";
if(isset($_REQUEST["out_trade_no"]) && $_REQUEST["out_trade_no"] != "") {
try{
$out_trade_no = $_REQUEST["out_trade_no"];
$input = new WxPayOrderQuery();
$input->SetOut_trade_no($out_trade_no);
$config = new WxPayConfig();
$result = WxPayApi::orderQuery($config, $input);
echo $result['trade_state'];
} catch(Exception $e) {
}
exit();
}
?>
<file_sep>/inc/class-wc-gateway-wepay-response.php
<?php
/*
* 异步通知的处理类
*/
ini_set('display_errors',1);
class WC_Gateway_Wepay_Response
{
private $gateway = null;
public function __construct($gateway) {
$this->gateway = $gateway;
// 有关woocommerce回调地址可以参考文档:
// https://docs.woocommerce.com/document/wc_api-the-woocommerce-api-callback/
// https://stackoverflow.com/questions/37293309/how-to-get-the-payment-response-url-in-woocommerce
add_action('woocommerce_api_wc_gateway_wepay', array($this, 'check_response'));
}
/*
* 验证请求中的签名,确保请求是来自于微信
*/
public function check_response() {
date_default_timezone_set('PRC'); //设置中国时区
//echo "hello";
//echo WCC_ALIPAY_PLUGIN_PATH;
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'WC_Gateway_Wepay_Response.txt', "check_response() 1 ".date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
//exit;
$config = new WxPayConfig();
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'WC_Gateway_Wepay_Response.txt', "check_response() 2 ".date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
$notify = new PayNotifyCallBack();
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'WC_Gateway_Wepay_Response.txt', "check_response() 3 ".date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
$notify->Handle($config, false);
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'WC_Gateway_Wepay_Response.txt', "check_response() 4 ".date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
}
}
<file_sep>/inc/class-wc-gateway-wepay-request.php
<?php
header("Content-type:text/html;charset=utf-8");
require_once WCC_WEPAY_PLUGIN_PATH."lib/WxPay.Api.php";
require_once WCC_WEPAY_PLUGIN_PATH."inc/WxPay.NativePay.php";
require_once WCC_WEPAY_PLUGIN_PATH."inc/WxPay.Config.php";
require_once WCC_WEPAY_PLUGIN_PATH.'inc/log.php';
/**
* 生成合法的请求url
*/
class WC_Gateway_Wepay_Request
{
private $gateway = null;
private $return_url = '';
private $out_trade_no = '';
public function __construct($gateway) {
$this->gateway = $gateway;
$this->notify_url = WC()->api_request_url('WC_Gateway_Wepay');
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'url.txt', WC()->api_request_url('WC_Gateway_Wepay').date("YmdHis").PHP_EOL, FILE_APPEND);
}
// 获得商户交易号
public function getOutTradeNo()
{
return $this->out_trade_no;
}
// 获得跳转url
public function getReturnUrl()
{
return $this->return_url;
}
/**
* 生成微信支付二维码(模式二)
* @param type $order 订单信息
* @return string url
*/
public function get_return_url($order) {
date_default_timezone_set('PRC'); //设置中国时区
// 刷卡支付实现类
$notify = new NativePay();
// 支付商品配置类
$input = new WxPayUnifiedOrder();
$product_body = '';
## For WooCommerce 3+ ##
// // Getting an instance of the WC_Order object from a defined ORDER ID
// $order = wc_get_order( $order_id );
// Iterating through each "line" items in the order
foreach ($order->get_items() as $item_id => $item_data) {
// Get an instance of corresponding the WC_Product object
$product = $item_data->get_product();
$product_name = $product->get_name(); // Get the product name
$item_quantity = $item_data->get_quantity(); // Get the item quantity
$item_total = $item_data->get_total(); // Get the item line total
// Displaying this data (to check)
//$product_body .= '商品: '.$product_name.' | 数量: '.$item_quantity.' | 总价: '. number_format( $item_total, 2 );
$product_body .= $product_name.' ';
}
$input->SetBody($product_body);
$input->SetAttach('编号为#'.$order->get_id().'的订单');
$this->out_trade_no = $order->get_id();
$this->return_url = $order->get_checkout_order_received_url();
$input->SetOut_trade_no($order->get_id());
// 最小单位是分
$input->SetTotal_fee($order->get_total() * 100);
//$input->SetTotal_fee("1");
$input->SetTime_start(date("YmdHis"));
//$input->SetTime_expire(date("YmdHis", time() + 1200));
$input->SetGoods_tag('编号为#'.$order->get_id().'的订单');
//$input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
$input->SetNotify_url($this->notify_url);
$input->SetTrade_type("NATIVE");
$input->SetProduct_id($order->get_id());
$result = $notify->GetPayUrl($input);
// print_r($result);
$url2 = $result["code_url"];
return $url2;
}
}<file_sep>/wcc-wepay.php
<?php
/*
* Plugin Name: WooCommerce Wepay Gateway
* Description: 微信网关
* Version: 1.0
* Author: Lucas
* Author URI: https://www.yuanpengfei.com
*/
// 防止文件直接被访问
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
// 定义常量
define('WCC_WEPAY_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('WCC_WEPAY_PLUGIN_URL', plugin_dir_url(__FILE__));
define('WCC_WEPAY_GATEWAY_ID', 'wcc_wepay');
// 创建二维码扫描页面
register_activation_hook( __FILE__, 'create_wepay_qrcode_page' );
function create_wepay_qrcode_page() {
$page_id = -1;
// 设置付款二维码页面
$author_id = 1;
$slug = 'wepay-page';
$title = 'Wepay_Qrcode_Page';
$wepay_page = get_page_by_title( $title );
// 检查该页面是否存在,如果不存在就新建
if ( null == $wepay_page) {
$wepay_page = array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => $slug,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'page'
);
// 此处要记录$post_id的值,此值为: www.xxx.com/?page_id=$post_id 未来显示二维码页面
$page_id = wp_insert_post( $wepay_page );
if ( !$page_id ) {
wp_die( 'Error creating template page' );
} else {
// 此处要记录www.xxx.com/?page_id=$post_id该链接
update_post_meta( $page_id, '_wp_page_template', 'template_wepay_qrcode_page.php' );
$wepay_qrcode_url = get_site_url(null, '/?page_id='.$page_id);
update_option( 'wepay_qrcode_url', $wepay_qrcode_url );
}
} else {
$wepay_qrcode_url = get_site_url(null, '/?page_id='.$wepay_page->ID);
update_option( 'wepay_qrcode_url', $wepay_qrcode_url );
}
}
// 创建付款查询页面
register_activation_hook( __FILE__, 'create_wepay_order_query_page' );
function create_wepay_order_query_page() {
$page_id = -1;
// 设置付款二维码页面
$author_id = 1;
$slug = 'wepay-page';
$title = 'Wepay_Order_Query_Page';
$wepay_page = get_page_by_title( $title );
// 检查该页面是否存在,如果不存在就新建
if ( null == $wepay_page) {
$wepay_page = array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => $slug,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'page'
);
// 此处要记录$post_id的值,此值为: www.xxx.com/?page_id=$post_id 未来显示二维码页面
$page_id = wp_insert_post( $wepay_page );
if ( !$page_id ) {
wp_die( 'Error creating template page' );
} else {
// 此处要记录www.xxx.com/?page_id=$post_id该链接
update_post_meta( $page_id, '_wp_page_template', 'template_wepay_order_query_page.php' );
$wepay_order_query_url = get_site_url(null, '/?page_id='.$page_id);
update_option( 'wepay_order_query_url', $wepay_order_query_url );
}
} else {
$wepay_order_query_url = get_site_url(null, '/?page_id='.$wepay_page->ID);
update_option( 'wepay_order_query_url', $wepay_order_query_url );
}
}
// 针对二维码页面,查询订单页面进行模板重定向
add_action( 'template_include', 'wepay_redirect' );
function wepay_redirect( $template ) {
// 跳转到二维码扫描页面
if ( is_page_template( 'template_wepay_qrcode_page.php' )) {
$template = WCC_WEPAY_PLUGIN_PATH . 'inc/class-wc-gateway-wepay-qrcode-show.php';
}
// 跳转到订单查询页面
if ( is_page_template( 'template_wepay_order_query_page.php' )) {
$template = WCC_WEPAY_PLUGIN_PATH . 'inc/class-wc-gateway-wepay-order-query.php';
}
return $template;
}
class WCC_Wepay
{
static private $instance = null;
private function __construct() {
add_action('plugins_loaded', array($this, 'init'));
}
private function __wakeup() {
}
private function __clone() {
}
static public function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
public function init() {
// 判断wcc是否启用,如果未启用,后续更多代码就不执行
if ( !in_array('woocommerce/woocommerce.php', get_option('active_plugins') ) ) {
return;
}
// 定义微信网关的核心类
include WCC_WEPAY_PLUGIN_PATH.'inc/class-wc-gateway-wepay.php';
// 引入其他的必要的文件
include WCC_WEPAY_PLUGIN_PATH.'inc/class-wc-gateway-wepay-response.php';
include WCC_WEPAY_PLUGIN_PATH.'inc/class-wc-gateway-wepay-request.php';
include WCC_WEPAY_PLUGIN_PATH.'inc/class-wc-gateway-wepay-notify.php';
// 告诉wcc你添加了一个新的网关
add_filter('woocommerce_payment_gateways', array($this, 'add_gatewawy'));
}
public function add_gatewawy($methods) {
$methods[] = 'WC_Gateway_Wepay';
return $methods;
}
}
WCC_Wepay::get_instance();
<file_sep>/inc/class-wc-gateway-wepay-notify.php
<?php
/**
*
* example目录下为简单的支付样例,仅能用于搭建快速体验微信支付使用
* 样例的作用仅限于指导如何使用sdk,在安全上面仅做了简单处理, 复制使用样例代码时请慎重
* 请勿直接直接使用样例对外提供服务
*
**/
//ini_set('date.timezone','Asia/Shanghai');
require_once WCC_WEPAY_PLUGIN_PATH."lib/WxPay.Api.php";
require_once WCC_WEPAY_PLUGIN_PATH.'lib/WxPay.Notify.php';
require_once WCC_WEPAY_PLUGIN_PATH."inc/WxPay.Config.php";
require_once WCC_WEPAY_PLUGIN_PATH.'inc/log.php';
//初始化日志
$logHandler= new CLogFileHandler(WCC_WEPAY_PLUGIN_PATH."logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);
class PayNotifyCallBack extends WxPayNotify
{
//查询订单
public function Queryorder($transaction_id)
{
$input = new WxPayOrderQuery();
$input->SetTransaction_id($transaction_id);
$config = new WxPayConfig();
$result = WxPayApi::orderQuery($config, $input);
Log::DEBUG("query:" . json_encode($result));
if(array_key_exists("return_code", $result)
&& array_key_exists("result_code", $result)
&& $result["return_code"] == "SUCCESS"
&& $result["result_code"] == "SUCCESS")
{
return true;
}
return false;
}
/**
*
* 回包前的回调方法
* 业务可以继承该方法,打印日志方便定位
* @param string $xmlData 返回的xml参数
*
**/
public function LogAfterProcess($xmlData)
{
Log::DEBUG("call back, return xml:" . $xmlData);
return;
}
//重写回调处理函数
/**
* @param WxPayNotifyResults $data 回调解释出的参数
* @param WxPayConfigInterface $config
* @param string $msg 如果回调处理失败,可以将错误信息输出到该方法
* @return true回调出来完成不需要继续回调,false回调处理未完成需要继续回调
*/
public function NotifyProcess($objData, $config, &$msg)
{
date_default_timezone_set('PRC'); //设置中国时区
$data = $objData->GetValues();
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'notify.txt', 'out_trade_no='.$data['out_trade_no'].date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
//TODO 1、进行参数校验
if(!array_key_exists("return_code", $data)
||(array_key_exists("return_code", $data) && $data['return_code'] != "SUCCESS")) {
//TODO失败,不是支付成功的通知
//如果有需要可以做失败时候的一些清理处理,并且做一些监控
$msg = "异常异常";
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'notify.txt', $msg.date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
return false;
}
if(!array_key_exists("transaction_id", $data)){
$msg = "输入参数不正确";
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'notify.txt', $msg.date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
return false;
}
//TODO 2、进行签名验证
try {
$checkResult = $objData->CheckSign($config);
if($checkResult == false){
//签名错误
Log::ERROR("签名错误...");
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'notify.txt', '签名错误'.date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
return false;
}
} catch(Exception $e) {
Log::ERROR(json_encode($e));
}
//TODO 3、处理业务逻辑
Log::DEBUG("call back:" . json_encode($data));
$notfiyOutput = array();
//查询订单,判断订单真实性
if(!$this->Queryorder($data["transaction_id"])){
$msg = "订单查询失败";
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'notify.txt', $msg.date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
return false;
} else {
$msg = "订单查询成功";
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'notify.txt', $msg.$data["out_trade_no"].date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
// 判断订单是否存在
$order = wc_get_order($data["out_trade_no"]);
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'notify.txt', '获得订单对象'.date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
// 增加一条订单备注
$date = date("Y-m-d H:i:s",time());
$msg = $date.' 顾客使用微信支付完成支付';
$order->add_order_note($msg);
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'notify.txt', '添加订单备注'.date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
// 更新订单状态、设置正确的库存
$order->payment_complete();
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'notify.txt', '更新订单状态、设置正确的库存'.date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
// 保存交易号
update_post_meta($order->get_id(), 'wepay_trade_no', $data["out_trade_no"]);
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'notify.txt', '保存交易号'.date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
}
file_put_contents(WCC_WEPAY_PLUGIN_PATH.'notify.txt', '回调调用true'.date("Y-m-d H:i:s",time()).PHP_EOL, FILE_APPEND);
return true;
}
}
//
//$config = new WxPayConfig();
//Log::DEBUG("begin notify");
//$notify = new PayNotifyCallBack();
//$notify->Handle($config, false);
<file_sep>/inc/class-wc-gateway-wepay.php
<?php
class WC_Gateway_Wepay extends WC_Payment_Gateway {
public function __construct() {
// 必要的字段
$this->id = WCC_WEPAY_GATEWAY_ID;
$this->icon = WCC_WEPAY_PLUGIN_URL.'assets/wepay.png';
$this->has_fields = false;
$this->method_title = '微信';
$this->method_description = '微信支付网关设置';
// 必须调用的方法
$this->init_form_fields();
$this->init_settings();
// 设置request或者response对象会用到的变量
$this->title = $this->get_option('title');
$this->description = $this->get_option('description');
$this->app_id = $this->get_option('app_id');
$this->mch_id = $this->get_option('mch_id');
$this->api_key = $this->get_option('api_key');
$this->notify_url = $this->get_option('notify_url');
// 保存后台设置的数据
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
// 实例化异步通知的处理
new WC_Gateway_Wepay_Response($this);
}
/*
* 处理支付宝付款
* 生成完整的支付宝付款的Url
* @param int $order_id
*/
public function process_payment($order_id) {
$request = new WC_Gateway_Wepay_Request($this);
$order = wc_get_order($order_id);
$url = $request->get_return_url($order);
return array(
'result' => 'success',
'redirect' => get_option( 'wepay_qrcode_url' ) . '&out_trade_no=' . $request->getOutTradeNo() . '&url=' . urlencode($url) . '&return_url=' . urlencode($request->getReturnUrl())
);
}
public function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => "启用/禁用",
'type' => 'checkbox',
'label' => "是否启用微信支付网关,勾选为启用",
'default' => 'yes',
),
'title' => array(
'title' => "标题",
'type' => 'text',
'description' => '在结算时看到的当前支付方式的名称',
'default' => '微信支付',
'desc_tip' => true,
),
'description' => array(
'title' => '描述',
'type' => 'text',
'desc_tip' => true,
'description' => '结算时当前支付方式的描述',
'default' => '将使用微信支付付款,打开微信App扫描二维码',
),
'app_id' => array(
'title' => 'APPID',
'type' => 'text',
'desc_tip' => true,
'description' => '腾讯提供的微信支付APPID',
'default' => '',
),
'mch_id' => array(
'title' => '商户号ID',
'type' => 'text',
'desc_tip' => true,
'description' => '支付宝给你提供的商户号ID,在微信商户平台产品中心->开发配置配置',
'default' => '',
),
'api_key' => array(
'title' => '商户支付API密钥',
'type' => 'text',
'desc_tip' => true,
'description' => '你创建的微信支付API密钥,在微信商户平台账户中心->API安全设置',
'default' => '',
),
'notify_url' => array(
'title' => '微信异步通知回调链接(不要修改)',
'type' => 'text',
'desc_tip' => true,
'description' => '你创建的微信支付API密钥,在微信商户平台账户中心->API安全设置',
'default' => $_SERVER['HTTP_HOST'].'/wc-api/WC_Gateway_Wepay/',
)
);
}
}
|
ad70958392352850269fb66daa16894970e7a11e
|
[
"Markdown",
"PHP"
] | 9
|
PHP
|
345161974/wcc-wepay
|
46a415ddeda51fdf51577efbf550c183abb1a4f2
|
4b74014044f15e2dc8481a105397a6fdfb7731df
|
refs/heads/master
|
<file_sep>var connection = require('./connection.js');
// Connect to MySQL database
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
};
console.log('connected as id ' + connection.threadId);
});
var orm = {
all: function(cb) {
connection.query('SELECT * FROM sausages', function (err, result) {
if (err) throw err;
console.log(orm);
cb(result);
});
},
insert: function(sausage_type, cb){
connection.query('INSERT INTO sausages SET ?', {
sausage_type: sausage_type,
devoured: false
}, function (err, result) {
if (err) throw err;
cb(result);
});
},
update: function(burgerID, cb){
// Run MySQL Query
connection.query('UPDATE sausages SET ? WHERE ?', [{devoured: true}, {id: id}], function (err, result) {
if (err) throw err;
cb(result);
});
}
};
// Export the ORM object in module.exports.
module.exports = orm;<file_sep>INSERT INTO sausages VALUES ("Hot Dog", true, "2016-09-27");
INSERT INTO sausages VALUES ("Bratwurst", true, "2015-02-21");
INSERT INTO sausages VALUES ("Frank", false, "2011-08-17");
INSERT INTO sausages VALUES ("Rabbit and Rattlesnake", true, "2017-12-01");
INSERT INTO sausages VALUES ("Hot Dog", true, "2016-09-27");
--YYYY-MM-DD HH:MM:SS<file_sep>CREATE DATABASE sausage_db;
USE burger_db;
-- Create the table plans.
CREATE TABLE sausages
(
id int NOT NULL AUTO_INCREMENT,
sausage_type varchar(255) NOT NULL,
devoured BOOLEAN,
createdAt TIMESTAMP NOT NULL,
PRIMARY KEY (id)
);
|
e7fcf65512e649d63d121ba716ce0afe07483adf
|
[
"JavaScript",
"SQL"
] | 3
|
JavaScript
|
nedmclean/burger
|
74d1990754f79004fd1295763b770289e7de9550
|
f3efc48b37b3090a44ab7f3c82c6f6cce23b691b
|
refs/heads/master
|
<repo_name>devadirad/User-Level-Thread-Library<file_sep>/ult/mypthread.c
#include "mypthread.h"
static mypthread_real threadPool[THREAD_COUNT];
static mypthread_t currThread;
static int countThreads = 1;
mypthread_t getUnusedThread() {
int i;
mypthread_t currThread = threadPool;
for(i=0; i < THREAD_COUNT; i++) {
if((currThread+i)->status == UNUSED) {
return currThread+i;
}
}
return NULL;
}
mypthread_t getPausedThread() {
int threadOffset;
threadOffset = (currThread == 0) ? 0 : currThread-threadPool;
//printf("t%d\t", threadOffset);
int i=0;
mypthread_real *currThread = threadPool;
for(i=threadOffset;i<countThreads;i++) {
if((currThread+i)->status == PAUSED) {
return currThread+i;
}
}
for(i=0;i<threadOffset;i++) {
if((currThread+i)->status == PAUSED) {
return currThread+i;
}
}
return NULL;
}
int mypthread_create(mypthread_t *thread, const mypthread_attr_t *attr, void *(*start_routine) (void *), void *arg)
{
if(countThreads == THREAD_COUNT-1) {
printf("Too many threads\n");
return -1;
}
mypthread_t ret;
ret = getUnusedThread();
if(ret == NULL) {
printf("Couldn't find UNUSED thread\n");
return -1;
}
countThreads++;
if(getcontext(&(ret->ctx)) != 0) {
fprintf(stderr, "Unable to get context\n");
return -1;
}
ret->ctx.uc_stack.ss_sp = ret->stk;
ret->ctx.uc_stack.ss_size = STACK_SIZE;
struct pthrarg *temp;
temp = (struct pthrarg *) arg;
makecontext(&(ret->ctx), (void (*)(void))start_routine, 1, arg);
ret->status = PAUSED;
*thread = ret;
return 0;
}
void mypthread_exit(void *retval) {
if(!currThread && (countThreads == 1)) {
exit(0);
}
currThread->status = UNUSED;
countThreads--;
if(countThreads == 0) {
exit(0);
}
if(currThread->parent) {
setcontext(&(currThread->parent->ctx));
}
currThread = getPausedThread();
if(!currThread) {
printf("Unable to find paused thread!");
}
currThread->status = ACTIVE;
if(setcontext(&(currThread->ctx)) == -1) {
printf("Unable to set context!");
}
}
int mypthread_yield(void) {
mypthread_t thread = getPausedThread();
if(thread == 0) {
printf("Error, either by user or yield getPausedThread() failed");
}
if(currThread == NULL) {
mypthread_t mainThread = getUnusedThread();
mainThread->status = PAUSED;
thread->status = ACTIVE;
currThread = thread;
if(swapcontext(&(mainThread->ctx), &(currThread->ctx)) == -1 ) {
printf("SwapContext failed\n");
return -1;
}
return 0;
}
mypthread_real *oldThread = currThread;
oldThread->status = PAUSED;
thread->status = ACTIVE;
currThread = thread;
if(setcontext(&(currThread->ctx)) == -1) {
fprintf(stderr, "Unable to set context!\n");
return -1;
}
return 0;
}
int mypthread_join(mypthread_t thread, void **retval) {
if(thread == 0) {
fprintf(stderr, "Something bad happened");
return -1;
}
if(thread->status == UNUSED) {
fprintf(stderr, "Recived uninitialized thread");
return -1;
}
if(currThread == NULL) {
mypthread_real *mainThread = getUnusedThread();
mainThread->status = WAITING;
thread->parent = mainThread;
thread->status = ACTIVE;
currThread = thread;
if(swapcontext(&(mainThread->ctx), &(currThread->ctx)) == -1 ) {
fprintf(stderr, "SwapContext failed\n");
return -1;
}
return 0;
}
mypthread_real *oldThread = currThread;
oldThread->status = WAITING;
thread->parent = currThread;
thread->status = ACTIVE;
currThread = thread;
if(swapcontext(&(oldThread->ctx), &(currThread->ctx)) == -1) {
fprintf(stderr, "Unable to set context!\n");
return -1;
}
return 0;
}<file_sep>/ult/mypthread-system-override.h
#ifndef H_MYPTHREAD
#define H_MYPTHREAD
#include <pthread.h>
#define mypthread_create pthread_create
#define mypthread_exit pthread_exit
#define mypthread_yield pthread_yield
#define mypthread_join pthread_join
#define mypthread_mutex_init pthread_mutex_init
#define mypthread_mutex_lock pthread_mutex_lock
#define mypthread_mutex_trylock pthread_mutex_trylock
#define mypthread_mutex_unlock pthread_mutex_unlock
#define mypthread_mutex_destroy pthread_mutex_destroy
#define mypthread_t pthread_t
#define mypthread_attr_t pthread_attr_t
#define mypthread_mutex_t pthread_mutex_t
#define mypthread_mutex_attr_t pthread_mutex_attr_t
#endif
|
5a1c8e4df5588cba38f1a1a39f8ac41456fb9a30
|
[
"C"
] | 2
|
C
|
devadirad/User-Level-Thread-Library
|
9d582e4d9e91fafdd4929d59e3868f388deff5b1
|
f1b96efe45d5341efa3653a2d48a4e40c2958e49
|
refs/heads/master
|
<repo_name>yash-kapila/LOLA-SGB-Style-Guide<file_sep>/app/style-guide/scripts/controllers/home-page.controller.js
(function() {
'use strict';
angular.module('macApp').controller('homePageController', HomePageController);
HomePageController.$inject = ['$scope', '$state'];
function HomePageController($scope, $state) {
var vm = this;
vm.initialize = function () {
vm.userForm = {
username: "",
address: "",
textArea: ""
};
};
vm.initialize();
}
})();<file_sep>/app/mac/components/form-elements/index.js
require('./radio-svg.scss');
require('./radio-styles.scss');
require('./styles.scss');<file_sep>/app/style-guide/views/index.js
require('./form-elements.template.html');
require('./typography.template.html');
require('./colors.template.html');
require('./buttons.template.html');
require('./dropdown.template.html');
require('./toggle-radio-buttons.template.html');
require('./home-page.template.html');<file_sep>/app/style-guide/scripts/controllers/index.js
require('./home-page.controller.js');
require('./form-elements.controller.js');
require('./colors.controller.js');
require('./dropdown.controller.js');
require('./toggle-radio-buttons.controller.js');<file_sep>/app/style-guide/scripts/controllers/colors.controller.js
(function() {
'use strict';
angular.module('macApp').controller('colorsController', ColorsController);
ColorsController.$inject = ['$scope', '$state'];
function ColorsController($scope, $state) {
var vm = this;
vm.colorCodeSelected = function(event, code) {
event.preventDefault();
vm.selectedColor = code;
};
vm.initialize = function () {
vm.selectedColor = 'primary';
};
vm.initialize();
}
})();<file_sep>/README.md
# LOLA-SGB-Style-Guide
Style Guide for LOLA SGB
## Installation ##
#### Install project dependencies ####
```bash
npm install -g gulp
npm install
```
## Local dev server ##
#### Run dev server for Style Guide application ####
```bash
gulp
```
Server will be running at: `http://localhost:8080/`
#### Run code checks ####
```bash
gulp lint
```
## Release build ##
#### Creates artificats for deployment purposes ####
```bash
gulp release
```
Output: `./_build/prod`
<file_sep>/app/mac/components/dropdown/index.js
require('./lola-dropdown.template.html');
require('./lola-dropdown.component.js');
require('./lola-dropdown.styles.scss'); <file_sep>/webpack.config.js
var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var envConfig = require('./config/environment.json');
var version = require('./package.json').version;
module.exports = function(env, mod){
var appConfig = envConfig[env];
var config = {
entry: {
vendor: mod.vendor,
main: mod.entry
},
output: {
path: __dirname+'/_build/'+env+'/'+mod.name,
filename: appConfig.hashAssets ? 'app.[chunkhash].js' : '[name].bundle.js'
},
resolve: {
modulesDirectories: ["node_modules",]
},
module: {
loaders: [
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader')},
{ test: /\.scss$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader')},
{ test: /\.html$/, loader: 'ngtemplate-loader?relativeTo=' + (path.resolve(__dirname, './app')) + '/!html'},
{ test: /\.(jpg|png|gif)$/, loader: 'file-loader?name=images/[name].[ext]'},
{ test: /\.(ttf|eot|woff|woff2|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader?name=fonts/[name].[ext]' }
]
},
plugins: [
new ExtractTextPlugin(appConfig.hashAssets ? './bundle.[chunkhash].css' : 'bundle.css'),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin()
]
};
/* For local environment */
if(appConfig.debug) {
config.debug = true;
config.devtool = 'sourcemap';
}
if(appConfig.env !== 'test') {
config.plugins = config.plugins.concat(
new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */appConfig.hashAssets ? "vendor.[chunkhash].js" : "vendor.js")
);
}
// local dev-server config
if(appConfig.env === 'local') {
config.devtool = 'eval';
for(var key in config.entry) {
config.entry[key].unshift(
'webpack-dev-server/client?http://localhost:8008/',
'webpack/hot/dev-server'
);
}
config.plugins = config.plugins.concat(
new webpack.HotModuleReplacementPlugin()
);
}
return config;
};
<file_sep>/app/mac/components/dropdown/lola-dropdown.component.js
(function () {
'use strict';
angular.module('macApp').component('lolaDropdown', {
templateUrl: require('./lola-dropdown.template.html'),
bindings: {
title: '@',
default: '<',
menuItems: '<',
onSelect: '&',
size: '@'
},
controller: 'lolaDropdown'
});
/**
*
*/
angular.module('macApp').controller('lolaDropdown', LolaDropdown);
function LolaDropdown() {
var vm = this;
vm.$onInit = function() {
if(vm.default){
vm.heading = vm.default.name;
vm.onSelect({id: vm.default.id});
}
else{
vm.heading = vm.title ? vm.title : "Select";
}
};
vm.itemSelected = function(option) {
vm.heading = option.name;
vm.onSelect({id: option.id});
};
}
})();<file_sep>/app/mac/components/toggle-buttons/index.js
require('./lola-toggle-buttons.template.html');
require('./lola-toggle-buttons.component.js');
require('./lola-toggle-buttons.styles.scss');<file_sep>/gulpfile.js
var gulp = require('gulp');
var gutil = require('gulp-util');
var inject = require('gulp-inject');
var jshint = require('gulp-jshint');
var express = require('express');
var webpackDevServer = require('webpack-dev-server');
var webpack = require('webpack');
var del = require('del');
var webpackConfig = require('./webpack.config.js');
var config = require('./config/config.json');
var html2js = require('gulp-html2js');
function getOutputPath(env, mod) {
return '_build/'+env+'/'+mod.name;
}
// build index.html
function buildIndexHtml(env, mod, done) {
var indexHtmlPath = mod.index;
var outputPath = __dirname+'/'+getOutputPath(env, mod);
var injectPaths = gulp.src([
outputPath+'/vendor*.js',
outputPath+'/*.js',
outputPath+'/*.css'
],{
read: false,
cwd: outputPath
});
return gulp.src(indexHtmlPath)
.pipe(inject(injectPaths, {addRootSlash: false}))
.pipe(gulp.dest(outputPath))
.on('end', done);
}
// build dev/uat/prod
function build(env, mod) {
return function(done) {
env = env || 'prod';
var outputPath = getOutputPath(env, mod);
gutil.log('[build]', 'Using \''+env.toUpperCase()+' '+mod.name.toUpperCase()+'\' config...');
var config = webpackConfig(env, mod);
// clean existing folder
gutil.log('[build]', 'Cleaning target directory...')
del.sync(['./'+outputPath+'/**/*']);
// run Webpack bundler
gutil.log('[build]', 'Running Webpack bundler...');
webpack(config, function(err, stats) {
if(err) {
throw new gutil.PluginError('build', err);
}
// build index.html
buildIndexHtml(env, mod, function(){
gutil.log('[build]', '\''+env.toUpperCase()+' '+mod.name.toUpperCase()+'\' build complete.');
done();
});
});
}
}
// dev-server
function server() {
return function(done) {
var env = 'local';
outputPath = getOutputPath(env, config);
gutil.log('[dev-server]', 'Using \''+env.toUpperCase()+' '+config.name.toUpperCase()+'\' config...');
var webpack_config = webpackConfig('local', config);
var onServerLoad = function(err, stats) {
if(err) {
throw new gutil.PluginError('dev-server', err);
}
build(env, config)(function(error) {
done(error);
});
};
//gutil.log('[dev-server]', 'Running Webpack bundler...');
new webpackDevServer(webpack(webpack_config, onServerLoad), {
contentBase: webpack_config.output.path,
publicPath: '/',
hot: true,
stats: {
colors: true
},
noInfo: true
}).listen(8008, 'localhost', function(err) {
if(err) {
throw new gutil.PluginError('dev-server', err);
}
});
}
}
// clean _build dir
gulp.task('clean', function() {
del.sync(['./_build/**']);
});
// JS Hint task
gulp.task('lint', function() {
return gulp.src('./app/scripts/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
// release tasks
gulp.task('release', build('prod', config));
// dev-server tasks
gulp.task('server:local', server());
gulp.task('html2Js', function () {
gulp.src('app/components/common/**/*.html')
.pipe(html2js('template.js', {
module: 'app.templates',
base: '.',
name: 'template-module',
options: { watch: true }
}))
.pipe(gulp.dest('app/components/common'));
});
gulp.task('watch', function() {
gulp.watch('app/components/common/**/*.html', ['html2Js'])
});
gulp.task('default', ['watch', 'server:local']);
<file_sep>/app/mac/components/toggle-buttons/lola-toggle-buttons.component.js
(function () {
'use strict';
angular.module('macApp').component('lolaToggleButtons', {
templateUrl: require('./lola-toggle-buttons.template.html'),
bindings: {
name: '@',
options: '<',
default: '<',
onSelect: '&'
},
controller: 'lolaToggleButtons'
});
/**
*
*/
angular.module('macApp').controller('lolaToggleButtons', LolaToggleButtons);
function LolaToggleButtons() {
var vm = this;
vm.$onInit = function() {
vm.selectedButton = vm.default ? vm.default : {};
};
vm.optionSelected = function(selectedButton) {
vm.onSelect({id: selectedButton.id});
};
}
})();<file_sep>/app/mac/components/index.js
require('./sass-mixins/index.js');
require('./dropdown/index.js');
require('./toggle-buttons/index.js');
require('./form-elements/index.js');
require('./typography/index.js');
require('./buttons/index.js');<file_sep>/app/index.js
/* Including bootstrap.min.css */
require('../node_modules/bootstrap/dist/css/bootstrap.min.css');
require('../node_modules/font-awesome/css/font-awesome.min.css');
/* Including style guide app files */
require('./style-guide/scripts/app.js');
require('./style-guide/scripts/index.js');
require('./style-guide/views/index.js');
require('./style-guide/styles/index.js');
/* Including mac app files */
require('./mac/index.js');
/* Including robot fonts */
require('./mac/fonts/Roboto-Bold.ttf');
require('./mac/fonts/Roboto-Light.ttf');
require('./mac/fonts/Roboto-Medium.ttf');
require('./mac/fonts/google.woff');<file_sep>/app/style-guide/views/dropdown.template.html
<div id="dropdown">
<h2 class='mac_heading'> Dropdowns </h2>
<p>
Dropdowns are styled using the Gel Framework as guide
with little tweaks specific to LOLA.
</p>
<p>
Provide <b>default</b> only in case an option needs to be pre-selected in the dropdown.
Otherwise, provide <b>title</b>.
</p>
<div class="container">
<table class="table table-bordered" style="table-layout: fixed">
<thead>
<tr>
<th> Browser View </th>
<th> HTML </th>
<th> Javascript </th>
</tr>
</thead>
<tbody>
<tr>
<td>
<lola-dropdown
title="Select & Add New"
default="dropdown.dropdown[0]"
menu-items="dropdown.dropdown"
on-select="dropdown.dropdownOptionSelected(id)">
</lola-dropdown>
<br>
</td>
<td>
<pre><code><lola-dropdown
title="Select & Add New"
default="dropdown[0]"
menu-items="dropdown"
on-select="dropdownOptionSelected(id)">
</lola-dropdown></code></pre>
</td>
<td>
<pre><code>vm.dropdown = [
{ id: 1, name: "Add Borrowing Entity" },
{ id: 2, name: "Add Facility" },
{ id: 3, name: "Add Security" },
{ id: 4, name: "Add Guarantee" }
]
vm.dropdownOptionSelected = function(id) {
console.log(id);
}
</code></pre>
</td>
</tr>
</tbody>
</table>
</div>
</div><file_sep>/app/style-guide/scripts/index.js
require('./controllers/index.js');
|
34c50e35820ece635a6689df161cdbd2b4bf6b88
|
[
"JavaScript",
"HTML",
"Markdown"
] | 16
|
JavaScript
|
yash-kapila/LOLA-SGB-Style-Guide
|
ed09ae86ccf52dbeacd06228907aedea61a2d26a
|
d60ae4ada5e2ee88edee64735012e758a94ded3c
|
refs/heads/master
|
<repo_name>sanyecao2314/ysoserial<file_sep>/src/main/java/ysoserial/RMIRegistryExploit.java
package ysoserial;
import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Arrays;
import java.util.concurrent.Callable;
import ysoserial.payloads.CommonsCollections1;
import ysoserial.payloads.ObjectPayload;
import ysoserial.payloads.util.Gadgets;
/*
* Utility program for exploiting RMI registries running with required gadgets available in their ClassLoader.
* Attempts to exploit the registry itself, then enumerates registered endpoints and their interfaces.
*
* TODO: automatic exploitation of endpoints, potentially with automated download and use of jars containing remote
* interfaces. See http://www.findmaven.net/api/find/class/org.springframework.remoting.rmi.RmiInvocationHandler .
*/
public class RMIRegistryExploit {
public static void main(final String[] args) throws Exception {
// ensure payload doesn't detonate during construction or deserialization
ExecBlockingSecurityManager.wrap(new Callable<Void>(){public Void call() throws Exception {
Registry registry = LocateRegistry.getRegistry(args[0], Integer.parseInt(args[1]));
String className = CommonsCollections1.class.getPackage().getName() + "." + args[2];
Class<? extends ObjectPayload> payloadClass = (Class<? extends ObjectPayload>) Class.forName(className);
Object payload = payloadClass.newInstance().getObject(args[3]);
Remote remote = Gadgets.createMemoitizedProxy(Gadgets.createMap("pwned", payload), Remote.class);
try {
registry.bind("pwned", remote);
} catch (Throwable e) {
e.printStackTrace();
}
try {
String[] names = registry.list();
for (String name : names) {
System.out.println("looking up '" + name + "'");
try {
Remote rem = registry.lookup(name);
System.out.println(Arrays.asList(rem.getClass().getInterfaces()));
} catch (Throwable e) {
e.printStackTrace();
}
}
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}});
}
}
<file_sep>/src/test/java/ysoserial/ExecSerializable.java
package ysoserial;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
@SuppressWarnings("serial")
public class ExecSerializable implements Serializable {
private final String cmd;
public ExecSerializable(String cmd) { this.cmd = cmd; }
private void readObject(final ObjectInputStream ois) {
try {
Runtime.getRuntime().exec("hostname");
} catch (IOException e) {
e.printStackTrace();
}
}
}<file_sep>/src/test/java/ysoserial/DeserializerThunk.java
package ysoserial;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.concurrent.Callable;
/*
* deserializes specified bytes; for use from isolated classloader
*/
public class DeserializerThunk implements Callable<Object> {
private final byte[] bytes;
public DeserializerThunk(byte[] bytes) { this.bytes = bytes; }
public Object call() throws Exception {
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
return ois.readObject();
}
}
|
80e21f944dd625f0f0d0ac6336de3e920c8ce458
|
[
"Java"
] | 3
|
Java
|
sanyecao2314/ysoserial
|
6a5e5b0713c175a10f2a74beef02393c23ca3b9e
|
02223116c15319ca187aa0828fdb027c9d690b44
|
refs/heads/master
|
<file_sep>package com.aforo255.app.seguridad.clients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import com.aforo255.app.seguridad.models.identity.Usuario;
@FeignClient(name="servicio-usuarios",url ="localhost:8003")
public interface UsuarioFeignClient {
@GetMapping("/usuarios/search/buscar-nombre")
public Usuario findByUsername(@RequestParam("nombre") String username);
@PutMapping("/usuarios/{id}")
public Usuario update(@RequestBody Usuario usuario, @PathVariable Long id);
}
<file_sep>spring.application.name=servicio-seguridad
server.port=8010
|
2df4ca9fcb2dd31f03e7251d58077e05da4640b4
|
[
"Java",
"INI"
] | 2
|
Java
|
Stywar/springboot-servicio-aforo255.seguridad
|
264650a53c0a518280f6425602f47715f837fdbc
|
b35a2be8abffd5a1d2d0278a1cf93650860b5a6c
|
refs/heads/master
|
<repo_name>NMyrholm/C-Lab01<file_sep>/Lab01/Program.cs
using System;
namespace Lab01
{
class Program
{
static void Main(string[] args)
{
Console.Write("Skriv in en söksträng: ");
var input = Console.ReadLine();
Console.WriteLine();
Search(input);
}
static void Search(string input)
{
long total = 0;
var firstIndex = 0;
foreach (var firstNumber in input)
{
var marked = "";
var secondIndex = firstIndex + 1;
foreach (var secondNumber in input.Substring(secondIndex))
{
if (secondNumber == firstNumber)
{
marked += input.Substring(firstIndex, secondIndex - firstIndex + 1);
//Before the marked number
Console.Write(input.Substring(0, firstIndex));
//The marked numbers
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write(marked);
Console.ForegroundColor = ConsoleColor.Gray;
//The rest of the string
Console.WriteLine(input.Substring(secondIndex + 1));
total += long.Parse(marked);
break;
}
if (!char.IsDigit(secondNumber)) break;
secondIndex++;
}
firstIndex++;
}
Console.WriteLine($"Totalen av alla markerade tal är: {total}");
}
}
}
|
de30252c9638e1797a0f8719e4089193819d447a
|
[
"C#"
] | 1
|
C#
|
NMyrholm/C-Lab01
|
8bb9c984c30bf15b5613084e367ed24a3aae6fac
|
3dec0aaf6bee769e3b0a6da02e7f0cd48567572e
|
refs/heads/master
|
<file_sep>import AnimatedNode from './AnimatedNode';
class AnimatedParam extends AnimatedNode {
constructor() {
super({ type: 'param' }, []);
this.__attach();
}
}
export function createAnimatedParam() {
return new AnimatedParam();
}
<file_sep>module.exports = api => {
api.cache(false);
return {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
'@babel/plugin-transform-modules-commonjs',
[
'module-resolver',
{
alias: {
'react-native-reanimated': '../src/Animated',
react: './node_modules/react',
'react-native': './node_modules/react-native',
'@babel': './node_modules/@babel',
fbjs: './node_modules/fbjs',
'hoist-non-react-statics': './node_modules/hoist-non-react-statics',
invariant: './node_modules/invariant',
'prop-types': './node_modules/prop-types',
},
},
],
],
};
};
<file_sep>import AnimatedNode from './AnimatedNode';
import { adapt } from './AnimatedBlock';
class AnimatedCallFunc extends AnimatedNode {
constructor(proc, args, params) {
super({
type: 'callfunc',
what: proc.__nodeID,
args: args.map(n => n.__nodeID),
params: params.map(n => n.__nodeID),
}, [...args]);
}
}
export function createAnimatedCallFunc(proc, args, params) {
return new AnimatedCallFunc(proc, args.map(p => adapt(p)), params);
}
|
b90305dc1b017d8915dc5d238f8e1c4176aff223
|
[
"JavaScript"
] | 3
|
JavaScript
|
PierreCapo/react-native-reanimated
|
0862993024b82e461e4080b318f43f98a412ccf2
|
da934e13516290b6c20df1d0a167abd9a3b3c9c8
|
refs/heads/master
|
<repo_name>bill611/cat_eye<file_sep>/src/drivers/uart.c
/*
* =============================================================================
*
* Filename: uart.c
*
* Description: uart driver
*
* Version: 1.0
* Created: 2016-08-06 16:45:01
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <strings.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <sys/times.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <pthread.h>
#include <sys/prctl.h>
#include <termios.h> //termios.tcgetattr(),tcsetattr
#include "hal_uart.h"
#include "uart.h"
#include "queue.h"
#include "debug.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static void uartReceiveCreate(UartServer * This);
static void uartSendCreate(UartServer * This);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
typedef struct {
uint32_t baudrate; // 波特率
uint8_t data_bit; // 数据长度
uint8_t parity; // 校验位
uint8_t stop_bit; // 停止位
}PortInfo ;
typedef struct _UartServerPriv {
int32_t fd;
uint8_t terminated;
Queue *queue;
pthread_mutex_t mutex; //队列控制互斥信号
PortInfo comparam; // linux接口使用
}UartServerPriv;
typedef struct _UartSendBuf{
int len;
uint8_t data[MAX_SEND_BUFF];
} UartSendBuf;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static void (*call_back_func)(void);
UartServer *uart = NULL;
/* ---------------------------------------------------------------------------*/
/**
* @brief uartOpen 打开串口
*
* @param This
* @param com 串口编号
* @param baudrate 波特率
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int uartOpen(UartServer *This,int com,int baudrate)
{
This->priv->fd = halUartOpen(com,
baudrate,
This->priv->comparam.data_bit,
This->priv->comparam.parity,
This->priv->comparam.stop_bit, NULL);
uartReceiveCreate(This);
uartSendCreate(This);
return This->priv->fd > 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief uartSend 发送数据
*
* @param This
* @param Buf
* @param datalen
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int uartSend(UartServer *This,void *Buf,int datalen)
{
UartSendBuf send_buf;
pthread_mutex_lock (&This->priv->mutex); //加锁
memset(&send_buf,0,sizeof(UartSendBuf));
send_buf.len = datalen;
memcpy(send_buf.data,Buf,datalen);
This->priv->queue->post(This->priv->queue,
&send_buf);
pthread_mutex_unlock (&This->priv->mutex); //解锁
return 1;
}
//---------------------------------------------------------------------------
static int uartRecvBuffer(UartServer *This,void *pBuf,uint32_t size)
{
int leave_size = size;
while(leave_size) {
int len = halUartRead(This->priv->fd,&((char*)pBuf)[size-leave_size],leave_size);
if(len <= 0)
break;
leave_size -= len;
usleep(20000);
}
return size-leave_size;
}
//---------------------------------------------------------------------------
static void uartClear(UartServer *This)
{
int result;
char cBuf[128];
do {
result = uartRecvBuffer(This,cBuf,sizeof(cBuf));
} while(result>0);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief uartClose 暂时关闭串口
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void uartClose(UartServer *This)
{
if(This->priv->fd) {
close(This->priv->fd);
This->priv->fd = 0;
This->priv->terminated = 1;
}
}
//---------------------------------------------------------------------------
static void * uartReceiveThead(UartServer *This)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
int fs_sel;
fd_set fs_read;
struct timeval tv_timeout;
while(!This->priv->terminated){
FD_ZERO(&fs_read);
FD_SET(This->priv->fd,&fs_read);
tv_timeout.tv_sec = 3;
tv_timeout.tv_usec = 0;
fs_sel = select(This->priv->fd+1,&fs_read,NULL,NULL,&tv_timeout);
if(fs_sel>0 && FD_ISSET(This->priv->fd,&fs_read)) {
if (call_back_func)
call_back_func();
}
}
pthread_exit(NULL);
}
static void * uartSendThead(UartServer *This)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
UartSendBuf send_buf;
while(!This->priv->terminated){
This->priv->queue->get(This->priv->queue, &send_buf);
halUartWrite(This->priv->fd, send_buf.data, send_buf.len);
DEBUG_UART("send",send_buf.data,send_buf.len);
usleep(500000);
}
pthread_exit(NULL);
}
static void uartReceiveCreate(UartServer * This)
{
int ret;
pthread_t id;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr,PTHREAD_SCOPE_SYSTEM);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
ret = pthread_create(&id,&attr,(void *)uartReceiveThead,This);
if(ret)
DPRINT("[%s pthread failt,Error code:%d\n",__FUNCTION__,ret);
pthread_attr_destroy(&attr);
}
static void uartSendCreate(UartServer * This)
{
int ret;
pthread_t id;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr,PTHREAD_SCOPE_SYSTEM);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
ret = pthread_create(&id,&attr,(void *)uartSendThead,This);
if(ret)
DPRINT("[%s pthread failt,Error code:%d\n",__FUNCTION__,ret);
pthread_attr_destroy(&attr);
}
static void uartDestroy(UartServer * This)
{
uartClose(This);
This->priv->terminated = 1;
pthread_mutex_destroy (&This->priv->mutex);
free(This);
}
UartServer *uartServerCreate(void (*func)(void))
{
pthread_mutexattr_t mutexattr;
UartServer *This = (UartServer *)calloc(1,sizeof(UartServer));
This->priv = (UartServerPriv *)calloc(1,sizeof(UartServerPriv));
pthread_mutexattr_init(&mutexattr);
/* Set the mutex as a recursive mutex */
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
/* create the mutex with the attributes set */
pthread_mutex_init(&This->priv->mutex, &mutexattr);
/* destroy the attribute */
pthread_mutexattr_destroy(&mutexattr);
call_back_func = func;
This->priv->queue =
queueCreate("uart_socket",QUEUE_BLOCK,sizeof(UartSendBuf));
// This->priv->comparam.baudrate = 38400;
This->priv->comparam.data_bit = 8;
This->priv->comparam.parity = 0;
This->priv->comparam.stop_bit = 1;
This->open = uartOpen;
This->close= uartClose;
This->send = uartSend;
This->recvBuffer = uartRecvBuffer;
This->clear = uartClear;
This->destroy = uartDestroy;
return This;
}
void uartInit(void(*func)(void))
{
uart = uartServerCreate(func);
uart->open(uart,1,9600);
}
<file_sep>/src/gui/my_controls/my_dialog.h
#ifndef _MGUI_CTRL_MYDIALOG_H
#define _MGUI_CTRL_MYDIALOG_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <minigui/common.h>
#include <minigui/minigui.h>
#include <minigui/gdi.h>
#include <minigui/window.h>
#include <minigui/control.h>
typedef struct {
// NOTIFPROC notif_proc;
/** Class name of the control */
const char* class_name;
/** Control style */
DWORD dwStyle;
/** Control position in dialog */
int x, y, w, h;
/** Control identifier */
int id;
/** Control caption */
const char* caption;
/** Additional data */
DWORD dwAddData;
/** Control extended style */
DWORD dwExStyle;
/** window element renderer name */
const char* werdr_name;
/** table of we_attrs */
const WINDOW_ELEMENT_ATTR* we_attrs;
PLOGFONT *font;
int font_color;
}MY_CTRLDATA;
typedef MY_CTRLDATA* PMY_CTRLDATA;
typedef struct {
/** Dialog box style */
DWORD dwStyle;
/** Dialog box extended style */
DWORD dwExStyle;
/** Dialog box position */
int x, y, w, h;
/** Dialog box caption */
const char* caption;
/** Dialog box icon */
HICON hIcon;
/** Dialog box menu */
HMENU hMenu;
/** Number of controls */
int controlnr;
/** Poiter to control array */
PMY_CTRLDATA controls;
/** Addtional data, must be zero */
DWORD dwAddData;
}MY_DLGTEMPLATE;
typedef MY_DLGTEMPLATE* PMY_DLGTEMPLATE;
HWND GUIAPI CreateMyWindowIndirectParamEx (PMY_DLGTEMPLATE pDlgTemplate,
HWND hOwner, WNDPROC WndProc, LPARAM lParam,
const char* werdr_name, WINDOW_ELEMENT_ATTR* we_attrs,
const char* window_name, const char* layer_name);
static inline HWND GUIAPI CreateMyWindowIndirectParam (
PMY_DLGTEMPLATE pDlgTemplate, HWND hOwner,
WNDPROC WndProc, LPARAM lParam)
{
return CreateMyWindowIndirectParamEx (pDlgTemplate, hOwner,
WndProc, lParam, NULL, NULL, NULL, NULL);
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* _MGUI_CTRL_ICONVIEW_H */
<file_sep>/module/singlechip/s_debug.c
/*
* =============================================================================
*
* Filename: UDPServer.c
*
* Description: udp驱动
*
* Version: 1.0
* Created: 2018-03-05 17:33:54
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "thread_helper.h"
#include "debug.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define CONSOLE_PATH "/tmp/consolename"
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static int stdio_redirect(void)
{
char tty[32] = {0};
int fd=open(CONSOLE_PATH, O_RDWR);
if (fd >= 0)
{
//获取要切换到的tty的名称
read(fd, tty, sizeof(tty));
printf("new console name %s \n", tty);
close(fd);
if((fd = open(tty, O_RDWR)) < 0)
{
printf("open file failed\r\n");
return -1;
}
//复制fd的文件表项到标准输出
dup2(fd, STDOUT_FILENO);
close(fd);
}
return -1;
}
static void * threadredirect(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
printf("tty %s \n", ttyname(1));
while(1)
{
if(access(CONSOLE_PATH, F_OK | R_OK | W_OK) >= 0) {
stdio_redirect();
unlink(CONSOLE_PATH);
}
sleep(2);
}
return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpServerInit 初始化udp服务
*
* @param port 侦听端口
*/
/* ---------------------------------------------------------------------------*/
void debugInit(void)
{
createThread(threadredirect,NULL);
}
<file_sep>/module/cap/CMakeLists.txt
set(MODULE_VIDEO
main.cpp
camera/md_camerahal.cpp
buffer/md_camerabuf.cpp
process/md_display_process.cpp
)
add_definitions(
-DLINUX -DSUPPORT_ION -DENABLE_ASSERT -DDEBUG
)
add_executable(cammer_cap ${MODULE_VIDEO})
target_link_libraries(cammer_cap
-Wl,--start-group
ion pthread cam_ia cam_engine_cifisp
drivers turbojpeg
-Wl,--end-group
)
<file_sep>/src/app/media_muxer.h
/*
* =============================================================================
*
* Filename: media_muxer.h
*
* Description: 音视频封装接口
*
* Version: 1.0
* Created: 2019-09-12 10:18:22
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MEDIA_MUXER_H
#define _MEDIA_MUXER_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <stdio.h>
#include <stdint.h>
#include <pthread.h>
#include "avilib/avilib.h"
#define WRITE_READ 0
#define READ_ONLY 1
typedef struct _CMPEG4Head {
FILE *hFile;
avi_t *avi_lib;
char filename[64]; //文件名,含路径
pthread_mutex_t mutex;
uint32_t dwFrameCnt; //视频流帧数
uint32_t dwAudioFrame; //音频流帧数
uint32_t dwStreamSize; //视频流大小
uint64_t dwStartTick;
uint64_t dwEndTick;
int FirstFrame; //是否是第一帧数据
int ReadFirstFrame; //是否已经读取第一帧
int m_Width;
int m_Height;
int InitVideoFrame;
int InitAudioFrame;
uint8_t bHaveAudio;
uint8_t bWriteAudio;
uint64_t mBlockSize;
uint32_t mChannels;
uint64_t mSample;
uint8_t m_ReadWrite; // 读写标志, =0写文件 =1读文件
int m_VideoType; // 视频类型 =0H264 =1divx
void (*InitAudio)(struct _CMPEG4Head *This, uint32_t Channels,uint64_t Sample,uint64_t dwBlockSize); //通道数,位率,块大小
uint8_t (*WriteVideo)(struct _CMPEG4Head *This, void *pData,uint32_t dwSize);
uint8_t (*WriteAudio)(struct _CMPEG4Head *This, void *pData,uint32_t dwSize);
int (*GetAviTotalTime)(struct _CMPEG4Head *This);
int (*GetAviFileFrameRate)(struct _CMPEG4Head *This);
int (*ReadAviData)(struct _CMPEG4Head *This, void *pData,uint64_t *dwSize,int *InCameraWidth,int *InCameraHeight);
void (*DestoryMPEG4)(struct _CMPEG4Head **This);
}MPEG4Head;
MPEG4Head* Mpeg4_Create(int Width,int Height,char *FileName, int ReadWrite);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/udp_talk/share_memory.c
/*
* =============================================================================
*
* Filename: share_memory.c
*
* Description: 共享内存管理
*
* Version: 1.0
* Created: 2019-07-27 16:21:13
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <semaphore.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "share_memory.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define MAXBUFCNT 5
#define SEM_PRG_GET "Prg_sem_get"
#define SEM_PRG_SAVE "Prg_sem_save"
struct ProcessData {
int size;
char data[1];
};
union ShareMemoryProcessData {
char *p;
struct ProcessData *process_buf;
};
typedef struct _ShareMemoryPrivate
{
int Type; // 0线程共享内存 非0进程共享内存
int shmid; // 共享内存id
int GetSemId; //读信号量
int SaveSemId; //写信号量
int Terminate; //结束
int MallocSize; //每段内存申请的大小
unsigned int MallocCnt; //分配多少段内存
char * Buf[MAXBUFCNT]; //内存指针
struct ProcessData *process_buf[MAXBUFCNT]; // 进程通信用该指针
int BufSize[MAXBUFCNT]; //内存的数据量
sem_t *GetSem; //读信号量
sem_t *SaveSem; //写信号量
int GetIndex; //读索引,用户只读
int SaveIndex; //写索引,用户只读
unsigned int WriteCnt; //写入的缓冲区数量
}ShareMemoryPrivate,*PShareMemoryPrivate;
union semun
{
int val;
struct semid_ds *buf;
unsigned short *arry;
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static int set_semvalue(int sem_id,int val)
{
//用于初始化信号量,在使用信号量前必须这样做
union semun sem_union;
sem_union.val = val;
if(semctl(sem_id, 0, SETVAL, sem_union) == -1)
return 0;
return 1;
}
static void del_semvalue(int sem_id)
{
//删除信号量
union semun sem_union;
if(semctl(sem_id, 0, IPC_RMID, sem_union) == -1)
fprintf(stderr, "F:delete semaphore:%s\n",strerror(errno));
}
static int semaphore_p(int sem_id)
{
// 对信号量做减1操作,即等待P(sv)
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_op = -1;//P()
sem_b.sem_flg = SEM_UNDO;
if(semop(sem_id, &sem_b, 1) == -1) {
fprintf(stderr, "F:semaphore_p failed:%s\n",strerror(errno));
return -1;
}
return 0;
}
static int semaphore_v(int sem_id)
{
//这是一个释放操作,它使信号量变为可用,即发送信号V(sv)
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_op = 1;//V()
sem_b.sem_flg = SEM_UNDO;
if(semop(sem_id, &sem_b, 1) == -1) {
fprintf(stderr, "F:semaphore_v failed:%s\n",strerror(errno));
return -1;
}
return 0;
}
/* ----------------------------------------------------------------*/
/**
* 线程操作时信号量处理
* @brief my_sem_post_get
* @brief my_sem_post_save
* @brief my_sem_wait_get
* @brief my_sem_wait_save
*
* @param This
*/
/* ----------------------------------------------------------------*/
static int thread_sem_post_get(PShareMemory This)
{
return sem_post(This->Private->GetSem);
}
static int thread_sem_post_save(PShareMemory This)
{
return sem_post(This->Private->SaveSem);
}
static int thread_sem_wait_get(PShareMemory This)
{
return sem_wait(This->Private->GetSem);
}
static int thread_sem_wait_save(PShareMemory This)
{
return sem_wait(This->Private->SaveSem);
}
/* ----------------------------------------------------------------*/
/**
* 进程操作时信号量处理
* @brief my_sem_post_get
* @brief my_sem_post_save
* @brief my_sem_wait_get
* @brief my_sem_wait_save
*
* @param This
*/
/* ----------------------------------------------------------------*/
static int process_sem_post_get(PShareMemory This)
{
return semaphore_v(This->Private->GetSemId);
}
static int process_sem_post_save(PShareMemory This)
{
return semaphore_v(This->Private->SaveSemId);
}
static int process_sem_wait_get(PShareMemory This)
{
return semaphore_p(This->Private->GetSemId);
}
static int process_sem_wait_save(PShareMemory This)
{
return semaphore_p(This->Private->SaveSemId);
}
//----------------------------------------------------------------------------
static void ShareMemory_CloseMemory(PShareMemory This)
{
unsigned int i;
This->Private->Terminate = 1;
if (This->Private->Type == 0) {
for(i=0;i<This->Private->MallocCnt;i++) {
This->My_sem_post_get(This);
This->My_sem_post_save(This);
}
} else {
for (i=0; i<This->Private->MallocCnt; i++) {
memset(This->Private->process_buf[i],0,This->Private->MallocSize);
}
set_semvalue(This->Private->GetSemId,0);
set_semvalue(This->Private->SaveSemId,This->Private->MallocCnt);
}
}
//----------------------------------------------------------------------------
// static void ShareMemory_InitSem(PShareMemory This)
// {
// unsigned int i;
// for(i=0;i<This->Private->MallocCnt;i++) {
// sem_post(This->Private->GetSem); //解除阻塞
// sem_post(This->Private->SaveSem);
// }
// }
//----------------------------------------------------------------------------
static void ShareMemory_Destroy(PShareMemory This)
{
unsigned int i;
This->Private->Terminate = 1;
if (This->Private->Type == 0) {
sem_destroy(This->Private->GetSem);
sem_destroy(This->Private->SaveSem);
for(i=0;i<This->Private->MallocCnt;i++) {
free(This->Private->Buf[i]);
This->Private->Buf[i] = NULL;
}
free(This->Private->SaveSem);
free(This->Private->GetSem);
} else {
del_semvalue(This->Private->GetSemId);
del_semvalue(This->Private->SaveSemId);
shmctl(This->Private->shmid, IPC_RMID,0);
}
free(This->Private);
free(This);
}
//----------------------------------------------------------------------------
static unsigned int ShareMemory_WriteCnt(PShareMemory This)
{
return This->Private->WriteCnt;
}
//----------------------------------------------------------------------------
static char * ShareMemory_SaveStart(PShareMemory This)
{
if(This->Private == NULL || This->Private->Terminate)
return NULL;
else {
This->My_sem_wait_save(This);
if (This->Private->Type == 0)
return This->Private->Buf[This->Private->SaveIndex];
else
return This->Private->process_buf[This->Private->SaveIndex]->data;
}
}
//----------------------------------------------------------------------------
static void ShareMemory_SaveEnd(PShareMemory This,int Size)
{
if(This->Private->WriteCnt<This->Private->MallocCnt)
This->Private->WriteCnt++;
if(Size>This->Private->MallocSize)
Size = This->Private->MallocSize;
if (This->Private->Type == 0)
This->Private->BufSize[This->Private->SaveIndex]=Size;
else
This->Private->process_buf[This->Private->SaveIndex]->size=Size;
This->My_sem_post_get(This);
This->Private->SaveIndex = (This->Private->SaveIndex+1) % This->Private->MallocCnt;
}
//----------------------------------------------------------------------------
static char * ShareMemory_GetStart(PShareMemory This,int *Size)
{
if(This->Private->Terminate || This->Private==NULL) {
*Size = 0;
return NULL;
} else {
if (This->My_sem_wait_get(This) == -1) {
*Size = 0;
return NULL;
}
if (This->Private->Type == 0) {
*Size = This->Private->BufSize[This->Private->GetIndex];
return This->Private->Buf[This->Private->GetIndex];
} else {
*Size = This->Private->process_buf[This->Private->GetIndex]->size;
return This->Private->process_buf[This->Private->GetIndex]->data;
}
}
}
//----------------------------------------------------------------------------
static void ShareMemory_GetEnd(PShareMemory This)
{
if(This->Private->WriteCnt)
This->Private->WriteCnt--;
This->My_sem_post_save(This);
This->Private->GetIndex = (This->Private->GetIndex+1) % This->Private->MallocCnt;
}
//----------------------------------------------------------------------------
/* ----------------------------------------------------------------*/
/**
* @brief CreateShareMemory 创建共享内存
*
* @param Size 内存大小
* @param BufCnt 内存块数
* @param ... 0为线程共享,非0为进程共享
*
* @returns
*/
/* ----------------------------------------------------------------*/
ShareMemory *CreateShareMemory(unsigned int Size,unsigned int BufCnt,int type)
{
int i;
PShareMemory This = (PShareMemory)calloc(sizeof(ShareMemory),1);
if(This == NULL) {
printf("F:Err: Creat This\n");
return NULL;
}
This->Private = (PShareMemoryPrivate)calloc(sizeof(ShareMemoryPrivate),1);
if(This->Private == NULL) {
free(This);
printf("F:Err: Creat This->Private\n");
return NULL;
}
This->Private->Type = type;
if (This->Private->Type == 0) {
if(BufCnt > MAXBUFCNT) {
BufCnt = MAXBUFCNT;
}
for(i=0;i<(int)BufCnt;i++) {
This->Private->Buf[i] = (char *)malloc(Size);
if(This->Private->Buf[i]==NULL) {
i--;
for(;i>=0;i--) {
free(This->Private->Buf[i]);
}
printf("F:Err: Creat Buf\n");
goto creat_err;
}
}
} else {
This->Private->shmid = shmget((key_t)1111,Size * BufCnt,IPC_CREAT | 0666);
if (This->Private->shmid < 0) {
fprintf(stderr, "F:Shmget:%s\n", strerror(errno));
goto creat_err;
}
char *sharemem = (char *)shmat(This->Private->shmid,NULL,0);
if (sharemem < 0) {
fprintf(stderr, "F:shmat:%s\n", strerror(errno));
goto creat_err;
}
for (i=0; i<(int)BufCnt; i++) {
This->Private->process_buf[i] = (struct ProcessData*)(sharemem + i*Size);
This->Private->process_buf[i]->size = 0;
}
}
if (This->Private->Type == 0) {
This->Private->GetSem = (sem_t *) malloc(sizeof(sem_t));
This->Private->SaveSem = (sem_t *) malloc(sizeof(sem_t));
sem_init (This->Private->GetSem, 0,0); //读信号量初始化为0
sem_init (This->Private->SaveSem, 0,BufCnt); //写信号量初始化为缓冲区数量
This->My_sem_post_get = thread_sem_post_get;
This->My_sem_post_save = thread_sem_post_save;
This->My_sem_wait_get = thread_sem_wait_get;
This->My_sem_wait_save = thread_sem_wait_save;
} else {
This->Private->GetSemId = semget((key_t)1234, 1, 0666 | IPC_CREAT);//sem_open(SEM_PRG_GET,O_CREAT,0666,0);
if (This->Private->GetSemId < 0) {
fprintf(stderr, "F:sem_open get:%s\n", strerror(errno));
goto creat_err;
}
This->Private->SaveSemId = semget((key_t)1236, 1, 0666 | IPC_CREAT);//sem_open(SEM_PRG_SAVE,O_CREAT,0666,BufCnt);
if (This->Private->SaveSemId < 0) {
fprintf(stderr, "F:sem_open save:%s\n", strerror(errno));
goto creat_err;
}
This->My_sem_post_get = process_sem_post_get;
This->My_sem_post_save = process_sem_post_save;
This->My_sem_wait_get = process_sem_wait_get;
This->My_sem_wait_save = process_sem_wait_save;
}
This->Private->Terminate = 0;
This->Private->MallocSize = Size;
This->Private->MallocCnt = BufCnt;
This->Private->GetIndex = 0;
This->Private->SaveIndex = 0;
This->Private->WriteCnt = 0;
This->Destroy = ShareMemory_Destroy;
// This->InitSem = ShareMemory_InitSem;
This->CloseMemory = ShareMemory_CloseMemory;
This->SaveStart = ShareMemory_SaveStart;
This->SaveEnd = ShareMemory_SaveEnd;
This->GetStart = ShareMemory_GetStart;
This->GetEnd = ShareMemory_GetEnd;
This->WriteCnt = ShareMemory_WriteCnt;
return This;
creat_err:
free(This->Private);
free(This);
return NULL;
}
ShareMemory * shareMemoryCreateMaster(unsigned int Size,unsigned int BufCnt)
{
PShareMemory This = CreateShareMemory(Size,BufCnt,1);
if (This) {
set_semvalue(This->Private->GetSemId,0);
set_semvalue(This->Private->SaveSemId,BufCnt);
}
return This;
}
ShareMemory * shareMemoryCreateSlave(unsigned int Size,unsigned int BufCnt)
{
return CreateShareMemory(Size,BufCnt,1);
}
<file_sep>/src/hal/hal_uart.h
/*
* =============================================================================
*
* Filename: hal_uart.h
*
* Description: 硬件层 串口驱动接口
*
* Version: 1.0
* Created: 2018-12-13 08:45:09
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _HAL_UART_H
#define _HAL_UART_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <stdint.h>
/* ---------------------------------------------------------------------------*/
/**
* @brief halUartOpen 硬件层 打开串口
*
* @param com 串口编号
* @param baudrate 波特率
* @param data_bit 数据长度
* @param parity 校验位
* @param stop_bit 停止位
* @param callback_func 接收回调函数,无则传NULL
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
int halUartOpen(int com,
int baudrate,
uint8_t data_bit,
uint8_t parity,
uint8_t stop_bit,
void *callback_func);
/* ---------------------------------------------------------------------------*/
/**
* @brief halUartRead 硬件层 串口读取
*
* @param fd 串口句柄
* @param buf 读出buf存储
* @param size 读出字节
*
* @returns 实际读出字节
*/
/* ---------------------------------------------------------------------------*/
int halUartRead(int fd,void *buf,uint32_t size);
/* ---------------------------------------------------------------------------*/
/**
* @brief halUartWrite 硬件层 串口写入
*
* @param fd 串口句柄
* @param buf 写入buf存储
* @param size 写入字节大小
*
* @returns 实际写入字节大小
*/
/* ---------------------------------------------------------------------------*/
int halUartWrite(int fd,void *buf,uint32_t size);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/module/cap/process/md_display_process.cpp
#include "md_display_process.h"
#include "thread_helper.h"
#include "h264_enc_dec/mpi_dec_api.h"
#include "jpeg_enc_dec.h"
#include "libyuv.h"
static FILE *fp = NULL;
DisplayProcess::DisplayProcess()
: StreamPUBase("DisplayProcess", true, true)
{
}
DisplayProcess::~DisplayProcess()
{
}
bool DisplayProcess::processFrame(std::shared_ptr<BufferBase> inBuf,
std::shared_ptr<BufferBase> outBuf)
{
unsigned char *data = (unsigned char *)inBuf->getVirtAddr();
if (fp == NULL)
return true;
unsigned char *jpeg_buf = NULL;
int size = 0;
yuv420spToJpeg(data,1280,720,&jpeg_buf,&size);
if (jpeg_buf) {
fwrite(jpeg_buf,1,size,fp);
fflush(fp);
fclose(fp);
free(jpeg_buf);
}
fp = NULL;
return true;
}
void DisplayProcess::capture(char *file_name)
{
while (fp != NULL) {
usleep(10000);
}
fp = fopen(file_name,"wb");
}
<file_sep>/module/updater/updater.cpp
#include <unistd.h>
#include <getopt.h>
#include "updater.h"
#include "md5sum.h"
#define SERVER_HTTP_ADDRESS "http://yourserver.com/"
#define FIREWARM_URL SERVER_HTTP_ADDRESS"Firmware.img"
#define FIREWARM_MD5_URL SERVER_HTTP_ADDRESS"Firmware.md5"
#define KERNEL_URL SERVER_HTTP_ADDRESS"kernel.img"
#define KERNEL_MD5_URL SERVER_HTTP_ADDRESS"kernel.md5"
#define DTB_URL SERVER_HTTP_ADDRESS"dtb"
#define DTB_MD5_URL SERVER_HTTP_ADDRESS"dtb.md5"
#define USERDATA_URL SERVER_HTTP_ADDRESS"userdata.img"
#define USERDATA_MD5_URL SERVER_HTTP_ADDRESS"userdata.md5"
#define BOOT_URL SERVER_HTTP_ADDRESS"sec-rootfs.img"
#define BOOT_MD5_URL SERVER_HTTP_ADDRESS"sec-rootfs.md5"
#define DOWNLOAD_PATH "/temp/"
#define LOCAL_FIREWARM_PATH "Firmware.img"
#define LOCAL_FIREWARM_MD5_PATH "Firmware.md5"
#define LOCAL_KERNEL_PATH "kernel.img"
#define LOCAL_KERNEL_MD5_PATH "kernel.md5"
#define LOCAL_DTB_PATH "dtb"
#define LOCAL_DTB_MD5_PATH "dtb.md5"
#define LOCAL_USERDATA_PATH "userdata.img"
#define LOCAL_USERDATA_MD5_PATH "userdata.md5"
int Updater::showTip(char *tipcap)
{
struct disp_cap cap;
if (mdisp != NULL) {
mdisp->RKDispClean();
sprintf(cap.str, tipcap);
cap.str_len = strlen(cap.str) * 8;
cap.y = 300;
cap.x = (mdisp->fbinfo.vinfo.xres - cap.str_len) >> 1;
cap.color = 0xFFFFFFFF;
mdisp->DrawString(cap);
}
return 0;
}
int Updater::prepare()
{
int ret;
mdisp = new RKDisplay();
if (mdisp == NULL) {
printf("RKDisplay instantiation failed\n");
return -1;
}
mpart = new RKPartition(mdisp);
if (mpart == NULL) {
printf("RKPartition instantiation failed\n");
return -1;
}
if (mpart->RKPartition_init() != 0) {
printf("RKPartition init failed\n");
return -1;
}
return 0;
}
int Updater::download(char* url)
{
return 0;
}
int Updater::download(int url_type)
{
switch (url_type) {
case URL_TYPE_FIRMWARE:
download((char *) FIREWARM_URL);
download((char *) FIREWARM_MD5_URL);
break;
case URL_TYPE_KERNEL:
download((char *) KERNEL_URL);
download((char *) KERNEL_MD5_URL);
break;
case URL_TYPE_DTB:
download((char *) DTB_URL);
download((char *) DTB_MD5_URL);
break;
case URL_TYPE_USERDATA:
download((char *) USERDATA_URL);
download((char *) USERDATA_MD5_URL);
case URL_TYPE_BOOT:
download((char *) BOOT_URL);
download((char *) BOOT_MD5_URL);
break;
default:
break;
}
return 0;
}
int Updater::checkEnvironment(char *path,int url_type)
{
char md5path[80];
char imagepath[80];
char verifymd5sum[MD5_LEN + 1];
char filemd5sum[MD5_LEN + 1];
switch (url_type) {
case URL_TYPE_FIRMWARE:
sprintf(imagepath,"%s%s" ,path,(char *)LOCAL_FIREWARM_PATH);
// strcpy(md5path, (char *)LOCAL_FIREWARM_MD5_PATH);
break;
case URL_TYPE_KERNEL:
sprintf(imagepath,"%s%s" ,path,(char *)LOCAL_KERNEL_PATH);
// strcpy(md5path, (char *)LOCAL_KERNEL_MD5_PATH);
break;
case URL_TYPE_DTB:
sprintf(imagepath,"%s%s" ,path,(char *)LOCAL_DTB_PATH);
// strcpy(md5path, (char *)LOCAL_DTB_MD5_PATH);
break;
case URL_TYPE_USERDATA:
sprintf(imagepath,"%s%s" ,path,(char *)LOCAL_USERDATA_PATH);
// strcpy(md5path, (char *)LOCAL_USERDATA_MD5_PATH);
default:
break;
}
// RKMD5::md5sum(imagepath, verifymd5sum);
// RKMD5::readmd5sum(md5path, filemd5sum);
// if (strcmp(filemd5sum, verifymd5sum) != 0) {
// printf("verify md5sum failed\n");
// return -1;
// }
mpart->setImagePath(imagepath);
mpart->setImageType(url_type);
if (mpart->checkPartitions(url_type) != 0) {
printf("checkPartitions failed\n");
return -1;
}
return 0;
}
int Updater::runCmd(char* cmd)
{
char buffer[BUFSIZ];
FILE* read_fp;
int chars_read;
int ret;
memset(buffer, 0, BUFSIZ);
read_fp = popen(cmd, "r");
if (read_fp != NULL) {
chars_read = fread(buffer, sizeof(char), BUFSIZ - 1, read_fp);
if (chars_read > 0) {
ret = 1;
} else {
ret = -1;
}
pclose(read_fp);
} else {
ret = -1;
}
return ret;
}
int Updater::waitAppEixt(char *app_name)
{
char cmd[128];
char buf[512];
char compare_str[20];
static int try_times = 0;
sprintf(cmd, "busybox killall %s", app_name);
runCmd(cmd);
usleep(100 * 1000);
sprintf(cmd, "ps | busybox grep %s", app_name);
sprintf(compare_str, "busybox grep %s", app_name);
FILE * fp = popen(cmd, "r");
if (!fp) {
perror("popen ps | grep wlan_setting fail");
return -1;
}
while (fgets(buf, sizeof(buf), fp)) {
try_times++;
if (try_times > 15) {
printf("wait_app_killer %s can not be killed! \n", app_name);
break;
}
if ( !strstr(buf, compare_str) && strstr(buf, app_name) && !strstr(buf, " Z ") ) {
puts(buf);
fclose(fp);
return 1;
}
}
fclose(fp);
return 0;
}
int Updater::doUpdate(int type)
{
bool rwkernel = false;
bool rwdtb = false;
bool rwuserdata = false;
bool rwboot = false;
switch (type) {
case UPDATE_KERNEL:
rwkernel = true;
break;
case UPDATE_DTB:
rwdtb = true;
break;
case UPDATE_USERDATA:
rwuserdata = true;
break;
case UPDATE_BOOT:
rwboot = true;
break;
case UPDATE_ALL:
rwkernel = true;
rwuserdata = true;
rwdtb = true;
rwboot = true;
default:
break;
}
if (rwdtb) {
if (mpart->update(PART_DTB) != 0) {
printf("update_kernel failed\n");
return -1;
}
}
if (rwkernel) {
if (mpart->update(PART_KERNEL) != 0) {
printf("update_kernel failed\n");
return -1;
}
}
if (rwuserdata) {
if (mpart->update(PART_USER) != 0) {
printf("update_userdata failed\n");
return -1;
}
}
if (rwboot) {
if (mpart->update(PART_BOOT) != 0) {
printf("update_userdata failed\n");
return -1;
}
}
}
Updater::Updater()
: mpart(NULL)
, mdisp(NULL)
{
}
Updater::~Updater()
{
if (mpart != NULL) {
delete mpart;
mpart = NULL;
}
if (mdisp != NULL) {
delete mdisp;
mdisp = NULL;
}
}
int main(int argc, char* argv[])
{
int opt;
int url_type = URL_TYPE_FIRMWARE;
int update_type = UPDATE_ALL;
char *path = NULL;
while (1) {
static struct option opts[] = {
{"image type", required_argument, 0, 'i'}, //all/kernel/dtb/user/boot
{"update part", required_argument, 0, 'p'}, //all/kernel/dtb/user/boot
{"help", no_argument, 0, 'h'},
};
int i = 0;
opt = getopt_long(argc, argv, "i:p:", opts, &i);
if (opt == -1)
break;
switch (opt) {
case 'i':
if (!strcmp(optarg, "all")) {
url_type = URL_TYPE_FIRMWARE;
update_type = UPDATE_ALL;
} else if (!strcmp(optarg, "kernel")) {
url_type = URL_TYPE_KERNEL;
update_type = UPDATE_KERNEL;
} else if (!strcmp(optarg, "dtb")) {
url_type = URL_TYPE_DTB;
update_type = UPDATE_DTB;
} else if (!strcmp(optarg, "user")) {
url_type = URL_TYPE_USERDATA;
update_type = UPDATE_USERDATA;
} else if (!strcmp(optarg, "boot")) {
url_type = URL_TYPE_BOOT;
update_type = UPDATE_BOOT;
}
break;
case 'p':
path = optarg;
break;
case 'h':
printf("updater -i [all/kernel/dtb/user/boot] -p imate_path\n");
printf("\t-i image type, default all\n");
printf("\t-p imate_path\n");
return 0;
}
}
Updater* updater = new Updater();
if (updater->prepare() != 0) {
printf("updater prepare failed\n");
return -1;
}
updater->showTip((char *)"wait for other app exit!");
printf("####to waitAppEixt:\n");
updater->waitAppEixt((char *)"cat_eye");
printf("####waitAppEixt done:\n");
printf("\n");
// updater->showTip((char *)"prepare for donwload image!");
// if (updater->download(url_type) != 0) {
// printf("updater checkEnvironment failed\n");
// return -1;
// }
updater->showTip((char *)"check image...");
if (updater->checkEnvironment(path,url_type) != 0) {
printf("updater checkEnvironment failed\n");
return -1;
}
if (updater->doUpdate(update_type) != 0) {
printf("updater failed\n");
updater->showTip((char *)"updater failed!");
return -1;
}
updater->showTip((char *)"updater success!");
delete updater;
updater = NULL;
// system("busybox reboot");
return 0;
}
<file_sep>/module/updater/wget/httpd.cpp
#include "httpd.h"
void Httpd::parse_url(const char *url, char *host, int *port, char *file_name)
{
int j = 0;
int start = 0;
*port = 80;
char *patterns[] = {"http://", "https://", NULL};
for (int i = 0; patterns[i]; i++)
if (strncmp(url, patterns[i], strlen(patterns[i])) == 0)
start = strlen(patterns[i]);
for (int i = start; url[i] != '/' && url[i] != '\0'; i++, j++)
host[j] = url[i];
host[j] = '\0';
char *pos = strstr(host, ":");
if (pos)
sscanf(pos, ":%d", port);
for (int i = 0; i < (int)strlen(host); i++) {
if (host[i] == ':') {
host[i] = '\0';
break;
}
}
j = 0;
for (int i = start; url[i] != '\0'; i++) {
if (url[i] == '/') {
if (i != strlen(url) - 1)
j = 0;
continue;
} else
file_name[j++] = url[i];
}
file_name[j] = '\0';
}
struct HTTP_RES_HEADER Httpd::parse_header(char *response)
{
struct HTTP_RES_HEADER resp;
char *pos = strstr(response, "HTTP/");
if (pos)
sscanf(pos, "%*s %d", &resp.status_code);
pos = strstr(response, "Content-Type:");
if (pos)
sscanf(pos, "%*s %s", resp.content_type);
pos = strstr(response, "Content-Length:");
if (pos)
sscanf(pos, "%*s %ld", &resp.content_length);
return resp;
}
void Httpd::get_ip_addr(char *host_name, char *ip_addr)
{
struct hostent *host = gethostbyname(host_name);
if (!host) {
ip_addr = NULL;
return;
}
for (int i = 0; host->h_addr_list[i]; i++) {
strcpy(ip_addr, inet_ntoa( * (struct in_addr*) host->h_addr_list[i]));
break;
}
}
void Httpd::progress_bar(long cur_size, long total_size, double speed)
{
float percent = (float) cur_size / total_size;
const int numTotal = 50;
int numShow = (int)(numTotal * percent);
int fixstrsize = (strlen("download : ") + strlen(filepath)) << 3;
if (numShow == 0)
numShow = 1;
if (numShow > numTotal)
numShow = numTotal;
char sign[51] = {0};
memset(sign, '=', numTotal);
if (RKdisp != NULL) {
if (cap.str_len != 0) {
cap_rect.w = cap.str_len - fixstrsize;
cap_rect.x = cap.x + fixstrsize;
RKdisp->DrawRect(cap_rect, 1, 0);
}
sprintf(cap.str, "download %s: %.2f%%", filepath, percent * 100);
cap.str_len = strlen(cap.str) * 8;
cap.y = 100;
cap.x = 80;
cap.color = 0xFFFFFFFF;
RKdisp->DrawString(cap);
cap_rect.x = cap.x;
cap_rect.y = cap.y;
cap_rect.w = cap.str_len;
cap_rect.h = 20;
}
printf("\r%.2f%%[%-*.*s] %.2f/%.2fMB %4.0fkb/s", percent * 100, numTotal, numShow, sign, cur_size / 1024.0 / 1024.0, total_size / 1024.0 / 1024.0, speed);
fflush(stdout);
if (numShow == numTotal)
printf("\n");
}
unsigned long Httpd::get_file_size(const char *filename)
{
struct stat buf;
if (stat(filename, &buf) < 0)
return 0;
return (unsigned long) buf.st_size;
}
void Httpd::download(int client_socket, char *file_name, long content_length)
{
long hasrecieve = 0;
struct timeval t_start, t_end;
int mem_size = 8192;
int buf_len = mem_size;
int len;
snprintf(filepath, sizeof(filepath), "%s%s", downpath, file_name);
int fd = open(filepath, O_CREAT | O_WRONLY, S_IRWXG | S_IRWXO | S_IRWXU);
if (fd < 0) {
printf("File creation failed!\n");
exit(0);
}
char *buf = (char *) malloc(mem_size * sizeof(char));
long diff = 0;
int prelen = 0;
double speed;
while (hasrecieve < content_length) {
gettimeofday(&t_start, NULL );
len = read(client_socket, buf, buf_len);
write(fd, buf, len);
gettimeofday(&t_end, NULL );
hasrecieve += len;
if (t_end.tv_usec - t_start.tv_usec >= 0 && t_end.tv_sec - t_start.tv_sec >= 0)
diff += 1000000 * ( t_end.tv_sec - t_start.tv_sec ) + (t_end.tv_usec - t_start.tv_usec);//us
if (diff >= 1000000) {
speed = (double)(hasrecieve - prelen) / (double)diff * (1000000.0 / 1024.0);
prelen = hasrecieve;
diff = 0;
}
progress_bar(hasrecieve, content_length, speed);
if (hasrecieve == content_length)
break;
}
close(fd);
}
Httpd::Httpd(RKDisplay *disp)
: RKdisp(disp)
{
strcpy(downpath, "/tmp/");
if (RKdisp != NULL) {
cap_rect.x = 0;
cap_rect.y = 300;
cap_rect.w = 480;
cap_rect.h = 20;
cap_rect.color = 0x0;
cap.str_len = 0;
RKdisp->RKDispClean();
}
}
Httpd::~Httpd()
{
}
int Httpd::get(char *url)
{
char host[64] = {0};
char ip_addr[16] = {0};
int port = 80;
char file_name[256] = {0};
puts("1: Parsing the download address...");
parse_url(url, host, &port, file_name);
puts("2: Getting the remote server IP address...");
get_ip_addr(host, ip_addr);
if (strlen(ip_addr) == 0) {
printf("Error: the remote server's IP address could not be obtained\n");
return -1;
}
puts("\n>>>>Download address resolved successfully<<<<");
printf("\tDownload address: %s\n", url);
printf("\tThe remote host : %s\n", host);
printf("\tIP address : %s\n", ip_addr);
printf("\tPORT : %d\n", port);
printf("\tDownpath : %s\n", downpath);
printf("\tFilename : %s\n\n", file_name);
char header[2048] = {0};
sprintf(header, \
"GET %s HTTP/1.1\r\n"\
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n"\
"User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537(KHTML, like Gecko) Chrome/47.0.2526Safari/537.36\r\n"\
"Host: %s\r\n"\
"Connection: keep-alive\r\n"\
"\r\n"\
, url, host);
puts("3: Create a network socket...");
int client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (client_socket < 0) {
printf("Create a network socket failed: %d\n", client_socket);
return -1;
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ip_addr);
addr.sin_port = htons(port);
puts("4: Connecting to remote host...");
int res = connect(client_socket, (struct sockaddr *) &addr, sizeof(addr));
if (res == -1) {
printf("Connecting to remote host, error: %d\n", res);
return -1;
}
puts("5: Sending an http download request...");
write(client_socket, header, strlen(header));
int mem_size = 4096;
int length = 0;
int len;
char *buf = (char *) malloc(mem_size * sizeof(char));
char *response = (char *) malloc(mem_size * sizeof(char));
puts("6: Parsing the http response header...");
while ((len = read(client_socket, buf, 1)) != 0) {
if (length + len > mem_size) {
mem_size *= 2;
char * temp = (char *) realloc(response, sizeof(char) * mem_size);
if (temp == NULL) {
printf("Dynamic memory request failed\n");
exit(-1);
}
response = temp;
}
buf[len] = '\0';
strcat(response, buf);
int flag = 0;
for (int i = strlen(response) - 1; response[i] == '\n' || response[i] == '\r'; i--, flag++);
if (flag == 4)
break;
length += len;
}
struct HTTP_RES_HEADER resp = parse_header(response);
printf("\n>>>>http response header resolved successfully:<<<<\n");
printf("\thttp response code: %d\n", resp.status_code);
if (resp.status_code != 200) {
printf("The file could not be downloaded, status_code: %d\n", resp.status_code);
return -1;
}
printf("\tHTTP content_type : %s\n", resp.content_type);
printf("\tHTTP content_length: %ldByte\n\n", resp.content_length);
printf("7: Start download...\n");
download(client_socket, file_name, resp.content_length);
printf("8: Close socket\n");
if (resp.content_length == get_file_size(filepath))
printf("\nfile %s download successful! ^_^\n\n", filepath);
else {
remove(filepath);
printf("\nThere is a byte missing in the file download, please try again!\n\n");
}
shutdown(client_socket, 2);
return 0;
}
int Httpd::setDownPath(char* path)
{
if (path != NULL)
strcpy(downpath, path);
return 0;
}
#if 0
int main(int argc, char const *argv[])
{
char url[2048];
if (argc == 1) {
printf("must be given an HTTP address to start working\n");
exit(-1);
} else {
strcpy(url, argv[1]);
}
Httpd* httpd = new Httpd();
httpd->get(url);
delete httpd;
httpd = NULL;
return 0;
}
#endif
<file_sep>/src/app/my_ntp.c
/*
* =============================================================================
*
* Filename: my_ntp.c
*
* Description: 同步时间
*
* Version: 1.0
* Created: 2019-05-21 16:45:16
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <time.h>
#include <stdarg.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>
#include "my_ntp.h"
#include "externfunc.h"
#include "thread_helper.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
//授时服务器 端口默认 123
#define DEF_NTP_SERVER "ntp.neu.edu.cn" //东北大学网络授时服务,为您提供高精度的网络授时服务
//#define DEF_NTP_SERVER_IP "192.168.3.11" //原始
#define DEF_NTP_SERVER_IP "172.16.17.32" //测试使用
#define DEF_NTP_PORT 123
//默认请求数据包填充
#define LI 0 //协议头中的元素
#define VN 3 //版本
#define MODE 3 //模式 : 客户端请求
#define STRATUM 0
#define POLL 4 //连续信息间的最大间隔
#define PREC -6 //本地时钟精度
//校验时间计算用到的宏
//ntp时间从年开始,本地时间从年开始,这是两者之间的差值
#define JAN_1970 0x83aa7e80 //3600s*24h*(365days*70years+17days)
//x*10^(-6)*2^32 微妙数转 NtpTime 结构的 fraction 部分
#define NTPFRAC(x) (4294 * (x) + ((1981 * (x)) >> 11))
//NTPFRAC的逆运算
#define USEC(x) (((x) >> 12) - 759 * ((((x) >> 10) + 32768) >> 16))
#define MKSEC(ntpt) ((ntpt).integer - JAN_1970)
#define MKUSEC(ntpt) (USEC((ntpt).fraction))
#define TTLUSEC(sec, usec) ((long long)(sec)*1000000 + (usec))
#define GETSEC(us) ((us) / 1000000)
#define GETUSEC(us) ((us) % 1000000)
#define DATA(i) ntohl(((unsigned int *)data)[i])
#define PDEBUG(fmt, args...) printf("[%s:%d]" fmt "\n", __func__, __LINE__, ##args)
//ntp时间戳结构
typedef struct
{
unsigned int integer;
unsigned int fraction;
} NtpTime;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static void (*getTimeCallBcak)(void);
static int need_update = 0; // 是否需要同步网络时间
static long update_period = 0; // 更新周期,减为0时立即更新
static pthread_mutex_t mutex ;
static void ntpSendPacket(int fd)
{
unsigned int data[12];
int ret;
struct timeval now;
if (sizeof(data) != 48) {
PDEBUG("data 长度小于48!");
return;
}
memset((char *)data, 0, sizeof(data));
data[0] = htonl((LI << 30) | (VN << 27) | (MODE << 24) | (STRATUM << 16) | (POLL << 8) | (PREC & 0xff));
data[1] = htonl(1 << 16);
data[2] = htonl(1 << 16);
//获得本地时间
gettimeofday(&now, NULL);
data[10] = htonl(now.tv_sec + JAN_1970);
data[11] = htonl(NTPFRAC(now.tv_usec));
ret = send(fd, data, 48, 0);
}
static int ntpGetServerTime(int sock, struct timeval *newtime)
{
int ret;
unsigned int data[12];
NtpTime oritime, rectime, tratime, destime;
struct timeval offtime, dlytime;
struct timeval now;
bzero(data, sizeof(data));
ret = recvfrom(sock, data, sizeof(data), 0, NULL, 0);
if (ret == -1) {
PDEBUG("读取返回数据失败\n");
return 1;
} else if (ret == 0) {
PDEBUG("读取到速度长度: 0!\n");
return 1;
}
//1970逆转换到1900
gettimeofday(&now, NULL);
destime.integer = now.tv_sec + JAN_1970;
destime.fraction = NTPFRAC(now.tv_usec);
//字节序转换
oritime.integer = DATA(6);
oritime.fraction = DATA(7);
rectime.integer = DATA(8);
rectime.fraction = DATA(9);
tratime.integer = DATA(10);
tratime.fraction = DATA(11);
//Originate Timestamp T1 客户端发送请求的时间
//Receive Timestamp T2 服务器接收请求的时间
//Transmit Timestamp T3 服务器答复时间
//Destination Timestamp T4 客户端接收答复的时间
//网络延时 d 和服务器与客户端的时差 t
//d = (T2 - T1) + (T4 - T3); t = [(T2 - T1) + (T3 - T4)] / 2;
long long orius, recus, traus, desus, offus, dlyus;
orius = TTLUSEC(MKSEC(oritime), MKUSEC(oritime));
recus = TTLUSEC(MKSEC(rectime), MKUSEC(rectime));
traus = TTLUSEC(MKSEC(tratime), MKUSEC(tratime));
desus = TTLUSEC(now.tv_sec, now.tv_usec);
offus = ((recus - orius) + (traus - desus)) / 2;
dlyus = (recus - orius) + (desus - traus);
offtime.tv_sec = GETSEC(offus);
offtime.tv_usec = GETUSEC(offus);
dlytime.tv_sec = GETSEC(dlyus);
dlytime.tv_usec = GETUSEC(dlyus);
struct timeval new;
//粗略校时
//new.tv_sec = tratime.integer - JAN_1970;
//new.tv_usec = USEC(tratime.fraction);
//精确校时
new.tv_sec = destime.integer - JAN_1970 + offtime.tv_sec;
new.tv_usec = USEC(destime.fraction) + offtime.tv_usec;
//提取现在好的时间
*newtime = new;
return 0;
}
/*
* 更新本地时间
* @newtime -- 要新的时间
* */
static int ntpModLocalTime(struct timeval newtime)
{
struct tm *tm_p;
time_t time_sec = newtime.tv_sec + 28800;
//time_t time_sec = newtime.tv_sec;
tm_p = gmtime(&time_sec);
#ifndef X86
adjustdate(tm_p->tm_year + 1900,
tm_p->tm_mon + 1,
tm_p->tm_mday,
tm_p->tm_hour,
tm_p->tm_min,
tm_p->tm_sec);
// system(time_buff);
#endif
if (getTimeCallBcak)
getTimeCallBcak();
return 0;
}
static void *ntpTimeThread(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
int ret;
int sock;
struct timeval newtime;
struct timeval timeout;
int addr_len = sizeof(struct sockaddr_in);
struct sockaddr_in addr_src; //本地 socket <netinet/in.h>
struct sockaddr_in addr_dst; //服务器 socket
//UDP数据报套接字
sock = socket(PF_INET, SOCK_DGRAM, 0);
if (sock == -1) {
PDEBUG("套接字创建失败,被迫终止 ! \n");
return NULL;
}
memset(&addr_src, 0, addr_len);
addr_src.sin_family = AF_INET;
addr_src.sin_port = htons(0);
addr_src.sin_addr.s_addr = htonl(INADDR_ANY); //<arpa/inet.h>
//绑定本地地址
if (-1 == bind(sock, (struct sockaddr *)&addr_src, addr_len))
{
PDEBUG("绑定失败,被迫终止 !\n");
goto end_thread;
}
memset(&addr_dst, 0, addr_len);
addr_dst.sin_family = AF_INET;
addr_dst.sin_port = htons(DEF_NTP_PORT);
addr_dst.sin_addr.s_addr = inet_addr((char *)arg);
if (-1 == connect(sock, (struct sockaddr *)&addr_dst, addr_len)) {
PDEBUG("连接服务器失败,被迫终止 !\n");
goto end_thread;
}
do {
if (!need_update) {
sleep(1);
continue;
}
if (update_period) {
pthread_mutex_lock(&mutex);
update_period--;
pthread_mutex_unlock(&mutex);
if (update_period > 0) {
sleep(1);
continue;
}
}
//发送 ntp 包
ntpSendPacket(sock);
fd_set fds_read;
FD_ZERO(&fds_read);
FD_SET(sock, &fds_read);
timeout.tv_sec = 30;
timeout.tv_usec = 0;
ret = select(sock + 1, &fds_read, NULL, NULL, &timeout);
if (ret == -1) {
PDEBUG("select函数出错,被迫终止 !\n");
break;
}
if (ret == 0) {
PDEBUG("等待服务器响应超时,重发请求 !\n");
sleep(1);
continue;
}
if (FD_ISSET(sock, &fds_read)) {
if (1 == ntpGetServerTime(sock, &newtime))
continue;
ntpModLocalTime(newtime);
pthread_mutex_lock(&mutex);
update_period = 60*60*24;
pthread_mutex_unlock(&mutex);
}
} while (1);
end_thread:
close(sock);
return NULL;
}
void ntpTime(char *server_ip,void (*callBack)(void))
{
getTimeCallBcak = callBack;
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
if (server_ip)
createThread(ntpTimeThread,server_ip);
}
void ntpEnable(int enable)
{
need_update = enable;
pthread_mutex_lock(&mutex);
update_period = 0;
pthread_mutex_unlock(&mutex);
}
<file_sep>/src/app/sql_handle.c
/*
* =============================================================================
*
* Filename: sqlHandle.c
*
* Description: 数据库存储操作接口
*
* Version: 1.0
* Created: 2018-05-21 22:48:19
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdint.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include "externfunc.h"
#include "sqlite3.h"
#include "sqlite.h"
#include "sql_handle.h"
#include "debug.h"
#include "config.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int sqlCheck(TSqlite *sql);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
struct DBTables {
char *name;
char **title;
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static pthread_mutex_t mutex;
static char *table_user = "CREATE TABLE IF NOT EXISTS UserInfo( \
ID INTEGER PRIMARY KEY,\
userId char(32) UNIQUE,\
type INTEGER, \
loginToken char(128),\
nickName char(128),\
scope INTEGER\
)";
static char *table_face = "CREATE TABLE IF NOT EXISTS FaceInfo( \
ID INTEGER PRIMARY KEY,\
userId char(32) UNIQUE,\
nickName char(128),\
fileURL char(256),\
feature BLOB\
)";
// 视频和抓图都用此接口
static char *table_record_cap = "CREATE TABLE IF NOT EXISTS RecordCapture( \
ID INTEGER PRIMARY KEY,\
date_time char(64),\
picture_id INTEGER\
)";
static char *table_record_alarm = "CREATE TABLE IF NOT EXISTS RecordAlarm( \
ID INTEGER PRIMARY KEY,\
date_time char(64),\
type INTEGER, \
hasPeople INTEGER, \
age INTEGER, \
sex INTEGER, \
picture_id INTEGER\
)";
static char *table_record_talk = "CREATE TABLE IF NOT EXISTS RecordTalk( \
ID INTEGER PRIMARY KEY,\
date_time char(64),\
people char(64),\
callDir INTEGER, \
answered INTEGER,\
talkTime INTEGER,\
picture_id INTEGER\
)";
static char *table_record_face = "CREATE TABLE IF NOT EXISTS RecordFace( \
ID INTEGER PRIMARY KEY,\
date_time char(64),\
faceId char(64),\
nickName char(128),\
picture_id INTEGER\
)";
static char *table_url_pic = "CREATE TABLE IF NOT EXISTS PicUrl( \
ID INTEGER PRIMARY KEY,\
picture_id INTEGER, \
url char(128)\
)";
static char *table_url_rec = "CREATE TABLE IF NOT EXISTS RecordUrl( \
ID INTEGER PRIMARY KEY,\
record_id INTEGER, \
url char(128)\
)";
static struct DBTables db_tables[] = {
{"UserInfo", &table_user},
{"FaceInfo", &table_face},
{"RecordCapture", &table_record_cap},
{"RecordAlarm", &table_record_alarm},
{"RecordTalk", &table_record_talk},
{"RecordFace", &table_record_face},
{"PicUrl", &table_url_pic},
{"RecordUrl", &table_url_rec},
{NULL,NULL}
};
static TSqliteData dbase = {
.file_name = DATABSE_PATH"database.db",
.sql = NULL,
.checkFunc = sqlCheck,
};
static int sqlCheck(TSqlite *sql)
{
if (sql == NULL)
goto sqlCheck_fail;
int ret = 1;
int i;
for (i=0; db_tables[i].name != NULL; i++) {
char buf[64];
sprintf(buf,"select ID from %s limit 1",db_tables[i].name);
int count = LocalQueryOpen(sql,buf);
sql->Close(sql);
if (count == 0) {
ret = 0;
}
}
if ( ret == 1 ) {
backData((char *)sql->file_name);
return TRUE;
}
sqlCheck_fail:
DPRINT("sql locoal err\n");
if (recoverData(dbase.file_name) == 0) {
for (i=0; db_tables[i].name != NULL; i++) {
DPRINT("creat new db:%s\n",db_tables[i].name);
LocalQueryExec(dbase.sql,*db_tables[i].title);
}
} else {
dbase.sql->Destroy(dbase.sql);
dbase.sql = CreateLocalQuery(dbase.sql->file_name);
}
sync();
return FALSE;
}
int sqlGetUserInfoStart(int type)
{
char buf[128];
sprintf(buf,"select * from UserInfo where type = %d",type );
pthread_mutex_lock(&mutex);
LocalQueryOpen(dbase.sql,buf);
return dbase.sql->RecordCount(dbase.sql);
}
void sqlGetUserInfos(
char *user_id,
char *nick_name,
int *scope)
{
*scope = LocalQueryOfInt(dbase.sql,"scope");
if (user_id)
LocalQueryOfChar(dbase.sql,"userId",user_id,32);
if (nick_name)
LocalQueryOfChar(dbase.sql,"nickName",nick_name,128);
dbase.sql->Next(dbase.sql);
}
int sqlGetUserInfoUseScopeStart(int scope)
{
char buf[128];
sprintf(buf,"select userId,nickName from UserInfo where scope = %d",scope );
if (pthread_mutex_trylock(&mutex) != 0)
return -1;
LocalQueryOpen(dbase.sql,buf);
return dbase.sql->RecordCount(dbase.sql);
}
void sqlGetUserInfosUseScope(
char *user_id,
char *nick_name)
{
if (user_id)
LocalQueryOfChar(dbase.sql,"userId",user_id,32);
if (nick_name)
LocalQueryOfChar(dbase.sql,"nickName",nick_name,128);
dbase.sql->Next(dbase.sql);
}
void sqlGetUserInfosUseScopeIndex(
char *user_id,
int scope,
int index)
{
char buf[128];
sprintf(buf,"select userId,nickName from UserInfo where scope = %d",scope );
pthread_mutex_lock(&mutex);
LocalQueryOpen(dbase.sql,buf);
while (index) {
dbase.sql->Next(dbase.sql);
index--;
}
if (user_id)
LocalQueryOfChar(dbase.sql,"userId",user_id,32);
pthread_mutex_unlock(&mutex);
}
int sqlGetUserInfoUseType(
int type,
char *user_id,
char *login_token,
char *nick_name,
int *scope)
{
char buf[128];
sprintf(buf,"select * from UserInfo where type = %d",type );
pthread_mutex_lock(&mutex);
LocalQueryOpen(dbase.sql,buf);
int ret = dbase.sql->RecordCount(dbase.sql);
if (ret) {
*scope = LocalQueryOfInt(dbase.sql,"scope");
if (user_id)
LocalQueryOfChar(dbase.sql,"userId",user_id,32);
if (login_token)
LocalQueryOfChar(dbase.sql,"loginToken",login_token,256);
if (nick_name)
LocalQueryOfChar(dbase.sql,"nickName",nick_name,128);
}
dbase.sql->Close(dbase.sql);
pthread_mutex_unlock(&mutex);
return ret;
}
int sqlGetUserInfoUseUserId(
char *user_id,
char *nick_name,
int *scope)
{
char buf[128];
sprintf(buf,"select * from UserInfo where userId = \"%s\"",user_id );
pthread_mutex_lock(&mutex);
LocalQueryOpen(dbase.sql,buf);
int ret = dbase.sql->RecordCount(dbase.sql);
if (ret) {
*scope = LocalQueryOfInt(dbase.sql,"scope");
if (nick_name)
LocalQueryOfChar(dbase.sql,"nickName",nick_name,128);
}
dbase.sql->Close(dbase.sql);
pthread_mutex_unlock(&mutex);
return ret;
}
void sqlGetUserInfoEnd(void)
{
dbase.sql->Close(dbase.sql);
pthread_mutex_unlock(&mutex);
}
void sqlInsertUserInfoNoBack(
char *user_id,
char *login_token,
char *nick_name,
int type,
int scope)
{
char buf[512];
pthread_mutex_lock(&mutex);
if (login_token)
sprintf(buf, "INSERT INTO UserInfo(userId,loginToken,nickName,type,scope) VALUES('%s','%s','%s','%d','%d')",
user_id, login_token,nick_name,type,scope);
else
sprintf(buf, "INSERT INTO UserInfo(userId,nickName,type,scope) VALUES('%s','%s','%d','%d')",
user_id, nick_name,type,scope);
printf("%s\n", buf);
LocalQueryExec(dbase.sql,buf);
pthread_mutex_unlock(&mutex);
}
void sqlInsertUserInfo(
char *user_id,
char *login_token,
char *nick_name,
int type,
int scope)
{
sqlInsertUserInfoNoBack(user_id,login_token,nick_name,type,scope);
dbase.checkFunc(dbase.sql);
}
void sqlDeleteDevice(char *id)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "Delete From UserInfo Where userId=\"%s\"", id);
DPRINT("%s\n",buf);
LocalQueryExec(dbase.sql,buf);
dbase.checkFunc(dbase.sql);
pthread_mutex_unlock(&mutex);
}
void sqlDeleteDeviceUseTypeNoBack(int type)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "Delete From UserInfo Where type=%d", type);
DPRINT("%s\n",buf);
LocalQueryExec(dbase.sql,buf);
dbase.checkFunc(dbase.sql);
pthread_mutex_unlock(&mutex);
}
int sqlGetDeviceId(uint16_t addr,char *id)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "select userId From UserInfo Where Addr=\"%d\"", addr);
LocalQueryOpen(dbase.sql,buf);
int ret = dbase.sql->RecordCount(dbase.sql);
if (ret)
LocalQueryOfChar(dbase.sql,"ID",id,32);
// DPRINT("ret:%d,id:%s\n", ret,id);
dbase.sql->Close(dbase.sql);
pthread_mutex_unlock(&mutex);
return ret;
}
void sqlSetEleQuantity(int value,char *id)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "UPDATE WifiList SET EleQuantity ='%d' Where id = \"%s\"",
value,id);
LocalQueryExec(dbase.sql,buf);
dbase.checkFunc(dbase.sql);
pthread_mutex_unlock(&mutex);
}
int sqlGetEleQuantity(char *id)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "select EleQuantity From WifiList Where ID=\"%s\"", id);
LocalQueryOpen(dbase.sql,buf);
int ret = LocalQueryOfInt(dbase.sql,"EleQuantity");
dbase.sql->Close(dbase.sql);
pthread_mutex_unlock(&mutex);
return ret;
}
void sqlInsertFace(char *user_id,
char *nick_name,
char *url,
void *feature,
int size)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "select nickName From FaceInfo Where userId=\"%s\"", user_id);
LocalQueryOpen(dbase.sql,buf);
int ret = dbase.sql->RecordCount(dbase.sql);
dbase.sql->Close(dbase.sql);
if (ret == 0) {
sprintf(buf, "INSERT INTO FaceInfo(userId,nickName,fileURL,feature) VALUES(?,?,?,?)");
} else {
sprintf(buf, "UPDATE FaceInfo SET userId=?,nickName=?,fileURL=?,feature=? WHERE userId = \"%s\"",user_id);
}
dbase.sql->prepare(dbase.sql,buf);
dbase.sql->bind_reset(dbase.sql);
dbase.sql->bind_text(dbase.sql,user_id);
dbase.sql->bind_text(dbase.sql,nick_name);
dbase.sql->bind_text(dbase.sql,url);
dbase.sql->bind_blob(dbase.sql,feature,size);
dbase.sql->step(dbase.sql);
dbase.sql->finalize(dbase.sql);
dbase.sql->Close(dbase.sql);
dbase.checkFunc(dbase.sql);
pthread_mutex_unlock(&mutex);
}
int sqlGetFaceCount(void)
{
pthread_mutex_lock(&mutex);
LocalQueryOpen(dbase.sql,"select userId From FaceInfo");
int ret = dbase.sql->RecordCount(dbase.sql);
dbase.sql->Close(dbase.sql);
pthread_mutex_unlock(&mutex);
return ret;
}
void sqlGetFaceStart(void)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "select userId,nickName,fileURL,feature From FaceInfo ");
dbase.sql->prepare(dbase.sql,buf);
}
int sqlGetFace(char *user_id,char *nick_name,char *url,void *feature)
{
int ret = dbase.sql->step(dbase.sql);
if (ret != SQLITE_ROW)
return 0;
dbase.sql->get_reset(dbase.sql);
dbase.sql->getBindText(dbase.sql,user_id);
dbase.sql->getBindText(dbase.sql,nick_name);
dbase.sql->getBindText(dbase.sql,url);
dbase.sql->getBlobData(dbase.sql,feature);
return 1;
}
void sqlGetFaceEnd(void)
{
dbase.sql->finalize(dbase.sql);
dbase.sql->Close(dbase.sql);
pthread_mutex_unlock(&mutex);
}
void sqlDeleteFace(char *id)
{
char buf[256];
pthread_mutex_lock(&mutex);
sprintf(buf, "Delete From FaceInfo Where userId=\"%s\"", id);
DPRINT("%s\n",buf);
LocalQueryExec(dbase.sql,buf);
dbase.checkFunc(dbase.sql);
pthread_mutex_unlock(&mutex);
}
void sqlInsertPicUrlNoBack(
uint64_t picture_id,
char *url)
{
pthread_mutex_lock(&mutex);
char buf[256];
if (url) {
sprintf(buf, "INSERT INTO PicUrl(picture_id,url) VALUES('%lld','%s')",
picture_id,url);
} else {
sprintf(buf, "INSERT INTO PicUrl(picture_id,url) VALUES('%lld','0')",
picture_id);
}
printf("%s\n", buf);
LocalQueryExec(dbase.sql,buf);
pthread_mutex_unlock(&mutex);
}
void sqlInsertRecordUrlNoBack(
uint64_t picture_id,
char *url)
{
pthread_mutex_lock(&mutex);
char buf[256];
if (url) {
sprintf(buf, "INSERT INTO RecordUrl(record_id,url) VALUES('%lld','%s')",
picture_id,url);
} else {
sprintf(buf, "INSERT INTO RecordUrl(record_id,url) VALUES('%lld','0')",
picture_id);
}
printf("%s\n", buf);
LocalQueryExec(dbase.sql,buf);
pthread_mutex_unlock(&mutex);
}
void sqlInsertRecordAlarm(
char *date_time,
int type,
int has_people,
int age,
int sex,
uint64_t picture_id)
{
char buf[256];
pthread_mutex_lock(&mutex);
sprintf(buf, "INSERT INTO RecordAlarm(date_time,type,hasPeople,age,sex,picture_id) VALUES('%s','%d','%d','%d','%d','%lld')",
date_time, type,has_people,age,sex,picture_id);
printf("%s\n", buf);
LocalQueryExec(dbase.sql,buf);
dbase.checkFunc(dbase.sql);
pthread_mutex_unlock(&mutex);
}
void sqlInsertRecordCapNoBack(
char *date_time,
uint64_t picture_id)
{
char buf[256];
pthread_mutex_lock(&mutex);
sprintf(buf, "INSERT INTO RecordCapture(date_time,picture_id) VALUES('%s','%lld')",
date_time, picture_id);
printf("%s\n", buf);
LocalQueryExec(dbase.sql,buf);
pthread_mutex_unlock(&mutex);
}
void sqlInsertRecordTalkNoBack(
char *date_time,
char *people,
int call_dir,
int answered,
int talk_time,
uint64_t picture_id)
{
char buf[256];
pthread_mutex_lock(&mutex);
sprintf(buf, "INSERT INTO RecordTalk(date_time,people,callDir,answered,talkTime,picture_id)\
VALUES('%s','%s','%d','%d','%d','%lld')",
date_time,people, call_dir,answered,talk_time,picture_id);
printf("%s\n", buf);
LocalQueryExec(dbase.sql,buf);
pthread_mutex_unlock(&mutex);
}
void sqlInsertRecordFaceNoBack(
char *date_time,
char *face_id,
char *nick_name,
uint64_t picture_id)
{
char buf[256];
pthread_mutex_lock(&mutex);
sprintf(buf, "INSERT INTO RecordFace(date_time,faceId,nickName,picture_id) VALUES('%s','%s','%s','%lld')",
date_time,face_id,nick_name,picture_id);
printf("%s\n", buf);
LocalQueryExec(dbase.sql,buf);
pthread_mutex_unlock(&mutex);
}
int sqlGetCapInfo(
uint64_t picture_id,
char *date_time)
{
char buf[128];
sprintf(buf,"select * from RecordCapture where picture_id = %lld",picture_id );
pthread_mutex_lock(&mutex);
LocalQueryOpen(dbase.sql,buf);
int ret = dbase.sql->RecordCount(dbase.sql);
printf("buf:%s,ret:%d\n", buf,ret);
if (ret) {
if (date_time)
LocalQueryOfChar(dbase.sql,"date_time",date_time,64);
}
dbase.sql->Close(dbase.sql);
pthread_mutex_unlock(&mutex);
return ret;
}
int sqlGetPicInfoStart(uint64_t picture_id)
{
char buf[128];
sprintf(buf,"select url from PicUrl where picture_id = %lld",picture_id );
pthread_mutex_lock(&mutex);
LocalQueryOpen(dbase.sql,buf);
return dbase.sql->RecordCount(dbase.sql);
}
void sqlGetPicInfos(char *url)
{
if (url)
LocalQueryOfChar(dbase.sql,"url",url,128);
dbase.sql->Next(dbase.sql);
}
void sqlGetPicInfoEnd(void)
{
dbase.sql->Close(dbase.sql);
pthread_mutex_unlock(&mutex);
}
int sqlGetRecordInfoStart(uint64_t picture_id)
{
char buf[128];
sprintf(buf,"select url from RecordUrl where record_id = %lld",picture_id );
pthread_mutex_lock(&mutex);
LocalQueryOpen(dbase.sql,buf);
return dbase.sql->RecordCount(dbase.sql);
}
void sqlGetRecordInfos(char *url)
{
if (url)
LocalQueryOfChar(dbase.sql,"url",url,128);
dbase.sql->Next(dbase.sql);
}
void sqlGetRecordInfoEnd(void)
{
dbase.sql->Close(dbase.sql);
pthread_mutex_unlock(&mutex);
}
int sqlGetAlarmInfoUseDateType(
char *date_time,
int type,
int *has_people)
{
char buf[128];
sprintf(buf,"select * from RecordAlarm where date_time = \"%s\" and type = %d",
date_time,type );
pthread_mutex_lock(&mutex);
LocalQueryOpen(dbase.sql,buf);
int ret = dbase.sql->RecordCount(dbase.sql);
printf("buf:%s,ret:%d\n", buf,ret);
if (ret) {
if (date_time)
LocalQueryOfChar(dbase.sql,"date_time",date_time,64);
*has_people = LocalQueryOfInt(dbase.sql,"hasPeople");
}
dbase.sql->Close(dbase.sql);
pthread_mutex_unlock(&mutex);
return ret;
}
void sqlClearFaceNoBack(void)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "Delete From FaceInfo");
DPRINT("%s\n",buf);
LocalQueryExec(dbase.sql,buf);
LocalQueryExec(dbase.sql,
"update sqlite_sequence set seq=0 where name='FaceInfo'");
pthread_mutex_unlock(&mutex);
}
void sqlClearDeviceNoBack(void)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "Delete From UserInfo");
DPRINT("%s\n",buf);
LocalQueryExec(dbase.sql,buf);
LocalQueryExec(dbase.sql,
"update sqlite_sequence set seq=0 where name='UserInfo'");
pthread_mutex_unlock(&mutex);
}
void sqlClearRecordCaptureNoBack(void)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "Delete From RecordCapture");
DPRINT("%s\n",buf);
LocalQueryExec(dbase.sql,buf);
LocalQueryExec(dbase.sql,
"update sqlite_sequence set seq=0 where name='RecordCapture'");
pthread_mutex_unlock(&mutex);
}
void sqlClearRecordTalkNoBack(void)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "Delete From RecordTalk");
DPRINT("%s\n",buf);
LocalQueryExec(dbase.sql,buf);
LocalQueryExec(dbase.sql,
"update sqlite_sequence set seq=0 where name='RecordTalk'");
pthread_mutex_unlock(&mutex);
}
void sqlClearRecordFaceNoBack(void)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "Delete From RecordFace");
DPRINT("%s\n",buf);
LocalQueryExec(dbase.sql,buf);
LocalQueryExec(dbase.sql,
"update sqlite_sequence set seq=0 where name='RecordFace'");
pthread_mutex_unlock(&mutex);
}
void sqlClearRecordAlarmNoBack(void)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "Delete From RecordAlarm");
DPRINT("%s\n",buf);
LocalQueryExec(dbase.sql,buf);
LocalQueryExec(dbase.sql,
"update sqlite_sequence set seq=0 where name='RecordAlarm'");
pthread_mutex_unlock(&mutex);
}
void sqlClearPicUrlNoBack(void)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "Delete From PicUrl");
DPRINT("%s\n",buf);
LocalQueryExec(dbase.sql,buf);
LocalQueryExec(dbase.sql,
"update sqlite_sequence set seq=0 where name='PicUrl'");
pthread_mutex_unlock(&mutex);
}
void sqlClearRecordUrlNoBack(void)
{
char buf[128];
pthread_mutex_lock(&mutex);
sprintf(buf, "Delete From RecordUrl");
DPRINT("%s\n",buf);
LocalQueryExec(dbase.sql,buf);
LocalQueryExec(dbase.sql,
"update sqlite_sequence set seq=0 where name='RecordUrl'");
pthread_mutex_unlock(&mutex);
}
void sqlCheckBack(void)
{
dbase.checkFunc(dbase.sql);
}
void sqlClearAll(void)
{
sqlClearFaceNoBack();
sqlClearDeviceNoBack();
sqlClearRecordCaptureNoBack();
sqlClearRecordTalkNoBack();
sqlClearRecordFaceNoBack();
sqlClearRecordAlarmNoBack();
sqlClearPicUrlNoBack();
sqlClearRecordUrlNoBack();
sqlCheckBack();
}
static void* threadSqlUpload(void *arg)
{
}
void sqlInit(void)
{
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
LocalQueryLoad(&dbase);
dbase.checkFunc(dbase.sql);
if (!dbase.sql) {
DPRINT("sql err\n");
}
}
<file_sep>/src/drivers/my_mixer.h
/*
* =====================================================================================
*
* Filename: Mixer.h
*
* Description: 创建混音器接口
*
* Version: 1.0
* Created: 2015-12-22 10:32:49
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
#ifndef _TMIXER_H
#define _TMIXER_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define FMT8K 8000
#define FMT22K 22050
#define FMT44K 44100
#define UDA_SET_RATE 0x101
#define UDA_SET_VOLUME 0x102
#define UDA_START_PLAY 0x103
#define UDA_START_REC 0x104
#define UDA_START_RP 0x105
#define UDA_STOP 0x106
#define UDA_GET_VOLUME 0x107
#define UDA_CTRLCLEARECHO 0x110
struct _TMixerPriv;
typedef enum {
ENUM_MIXER_CLEAR_NONE = 0x00,
ENUM_MIXER_CLEAR_PLAY_BUFFER= 0x01,
ENUM_MIXER_CLEAR_REC_BUFFER = 0x02,
ENUM_MIXER_CLEAR_ALL_BUFFER = 0xff
}ENUM_MIXER_CLEAR_TYPE;
typedef struct _TMixer
{
struct _TMixerPriv *Priv;
void (*Destroy)(struct _TMixer *);
int (*Open)(struct _TMixer *,int Sample,int CH);
int (*Close)(struct _TMixer *,int *Handle);
int (*Read)(struct _TMixer *,void *pBuffer,int Size,int channel);
int (*ReadBuf)(struct _TMixer *,void *AudioBuf,int NeedSize,int channel);
int (*WriteBuffer)(struct _TMixer *,int Handle,const void *pBuffer,int Size);
int (*Write)(struct _TMixer *,int Handle,const void *pBuffer,int Size);
void (*InitVolume)(struct _TMixer *,int Volume,int bSlience); //初始化音量
int (*GetVolume)(struct _TMixer *,int type); //返回音量
int (*SetVolume)(struct _TMixer *,int Volume,int type); //设置音量
int (*SetVolumeEx)(struct _TMixer *,int Volume); //用外部函数设置音量
void (*SetSlience)(struct _TMixer *,int bSlience); //设置是否静音
int (*GetSlience)(struct _TMixer *); //返回是否静音
void (*ClearRecBuffer)(struct _TMixer *);
void (*ClearPlayBuffer)(struct _TMixer *);
void (*InitPlayAndRec)(struct _TMixer *, int *handle,int sample,int channle);
void (*InitPlay8K)(struct _TMixer *, int *handle);
void (*DeInitPlay)(struct _TMixer *, int *handle);
void (*DeInitPlay8K)(struct _TMixer *, int *handle);
} TMixer;
//创建一个混音器
TMixer* mixerCreate(void);
void myMixerInit(void);
extern TMixer *my_mixer;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/include/mpi/mpp_platform.h
/*
* Copyright 2015 Rockchip Electronics Co. LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __MPP_PLATFORM__
#define __MPP_PLATFORM__
#include "mpp_sdk_interface.h"
/*
* Platform flag detection is for rockchip hardware platform detection
*/
#ifdef __cplusplus
extern "C" {
#endif
/*
* Platform video codec hardware feature
*/
/* RK combined codec */
#define HAVE_VPU1 (0x00000001)
#define HAVE_VPU2 (0x00000002)
/* RK standalone decoder */
#define HAVE_HEVC_DEC (0x00000100)
#define HAVE_RKVDEC (0x00000200)
#define HAVE_AVSDEC (0x00001000)
/* RK standalone encoder */
#define HAVE_RKVENC (0x00010000)
#define HAVE_VEPU (0x00020000)
/* External encoder */
#define HAVE_H265ENC (0x01000000)
/*
* Platform image process hardware feature
*/
#define HAVE_IPP (0x00000001)
#define HAVE_RGA (0x00000002)
#define HAVE_RGA2 (0x00000004)
#define HAVE_IEP (0x00000008)
const char *mpp_get_soc_name(void);
RK_U32 mpp_get_vcodec_type(void);
RK_U32 mpp_get_2d_hw_flag(void);
const char *mpp_get_platform_dev_name(MppCtxType type, MppCodingType coding, RK_U32 platform);
const char *mpp_get_vcodec_dev_name(MppCtxType type, MppCodingType coding);
#ifdef __cplusplus
}
#endif
#endif /*__MPP_PLATFORM__*/
<file_sep>/src/hal/hal_gpio.h
/*
* =============================================================================
*
* Filename: hal_gpio.h
*
* Description: 硬件层 GPIO控制
*
* Version: 1.0
* Created: 2018-12-12 16:28:49
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _HAL_GPIO_H
#define _HAL_GPIO_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
enum {
HAL_INPUT, // 输入
HAL_OUTPUT, // 输出
};
/* ---------------------------------------------------------------------------*/
/**
* @brief halGpioSetMode 硬件层 设置IO为输入或输出
*
* @param port_id IO编号
* @param port_mask IO码 (针对GPIOA,0123...的情况,没有则填-1)
* @param dir IO方向, HAL_INPUT或HAL_OUTPUT
*/
/* ---------------------------------------------------------------------------*/
void halGpioSetMode(int port_id,char *port_name,int dir);
/* ---------------------------------------------------------------------------*/
/**
* @brief halGpioOut 硬件层 设置输出电平
*
* @param port_id
* @param port_mask
* @param value 0低电平 1高电平
*/
/* ---------------------------------------------------------------------------*/
void halGpioOut(int port_id,char *port_name,int value);
/* ---------------------------------------------------------------------------*/
/**
* @brief halGpioIn 硬件层 获取电平输入值
*
* @param port_id
* @param port_mask
*
* @returns 0低电平 1高电平
*/
/* ---------------------------------------------------------------------------*/
int halGpioIn(int port_id,char * port_name);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/cmk
#!/bin/bash
cmake_dir=
if [ $# == 0 ]; then
cmake_dir=release
mkdir -p $cmake_dir
cd $cmake_dir
cmake \
-DCMAKE_BUILD_TYPE=Release \
-DMODE_UART=OFF \
\
..
elif [ $1 == "debug" ]; then
cmake_dir=debug
mkdir -p $cmake_dir
cd $cmake_dir
cmake \
-DCMAKE_BUILD_TYPE=Debug \
-DMODE_UART=OFF \
-DAUTO_SLEEP=OFF \
..
elif [ $1 == "x86" ]; then
cmake_dir=x86
mkdir -p $cmake_dir
cd $cmake_dir
cmake \
-DCMAKE_BUILD_TYPE=Debug \
-DPLATFORM_RV1108=OFF \
-DMODE_VIDEO=OFF \
-DMODE_FACE=OFF \
-DMODE_UCPAAS=OFF \
-DAUTO_SLEEP=OFF \
..
fi
make
if [ $? == 0 ]; then
cd ..
if [[ $# == 0 || $1 == "debug" ]]; then
if [ $# == 0 ]; then
$RV1108_CROOS_PATH/bin/arm-linux-strip $cmake_dir/cat_eye
cp $cmake_dir/cat_eye ../burn/root_usr/
cp $cmake_dir/cat_eye $RV1108_SDK_PATH/common/overlay/usr/
cp $cmake_dir/cat_eye update/app/update/root/usr
cp $cmake_dir/cat_eye update/img/update
$RV1108_CROOS_PATH/bin/arm-linux-strip $cmake_dir/cammer_video
cp $cmake_dir/cammer_video ../burn/userdata
cp $cmake_dir/cammer_video $RV1108_SDK_PATH/common/userdata/
$RV1108_CROOS_PATH/bin/arm-linux-strip $cmake_dir/cammer_cap
cp $cmake_dir/cammer_cap ../burn/userdata
cp $cmake_dir/cammer_cap $RV1108_SDK_PATH/common/userdata/
$RV1108_CROOS_PATH/bin/arm-linux-strip $cmake_dir/singlechip
cp $cmake_dir/singlechip ../burn/userdata
cp $cmake_dir/singlechip $RV1108_SDK_PATH/common/userdata/
$RV1108_CROOS_PATH/bin/arm-linux-strip $cmake_dir/red
cp $cmake_dir/red ../burn/root_usr/
cp $cmake_dir/red $RV1108_SDK_PATH/common/overlay/usr/
fi
cp $cmake_dir/cat_eye ~/arm_share/cat_eye/
cp $cmake_dir/singlechip ~/arm_share/cat_eye/
cp $cmake_dir/cammer_video ~/arm_share/cat_eye/
cp $cmake_dir/updater ~/arm_share/cat_eye/
cp $cmake_dir/updater update/img/update
cd update/app
tar czf Update.tar.gz update/
cp Update.tar.gz ../../$cmake_dir/update.cab
mv Update.tar.gz ../../$cmake_dir/update_cateye_v.tgz
cd ../img
tar czf update_img.tar.gz update/
mv update_img.tar.gz ../../$cmake_dir/
cd ../../
fi
fi
<file_sep>/src/app/video/video_server.cpp
#include <list>
#include "camerahal.h"
#include "camerabuf.h"
#include "thread_helper.h"
#include "process/display_process.h"
#include "process/face_process.h"
#include "process/encoder_process.h"
#include "queue.h"
enum {
MSG_DISPLAY_LOCAL,
MSG_DISPLAY_PEER,
MSG_DISPLAY_OFF,
};
struct StVideoServer{
int msg;
long p_data_addr;
int w,h;
int type;
};
static Queue *queue = NULL; // 显示本地或远程视频消息队列
extern "C"
void cammerErrorToPowerOff(void);
class RKVideo {
public:
RKVideo();
~RKVideo();
int connect(std::shared_ptr<CamHwItf::PathBase> mpath,
std::shared_ptr<StreamPUBase> next,
frm_info_t& frmFmt, const uint32_t num,
std::shared_ptr<RKCameraBufferAllocator> allocator);
void disconnect(std::shared_ptr<CamHwItf::PathBase> mpath,
std::shared_ptr<StreamPUBase> next);
void displayPeer(int w,int h,void* decCallback);
void displayLocal(void);
void displayOff(void);
void faceOnOff(bool type);
void h264EncOnOff(bool type,int w,int h,EncCallbackFunc encCallback);
void capture(char *file_name);
void recordStart(int w,int h,EncCallbackFunc recordCallback);
void recordSetStopFunc(RecordStopCallbackFunc recordCallback);
void recordStop(void);
int getCammerState(void);
private:
int display_state_; // 0关闭 1本地视频 2远程视频
bool face_state_;
bool h264enc_state_;
struct rk_cams_dev_info cam_info;
std::shared_ptr<RKCameraBufferAllocator> ptr_allocator;
CameraFactory cam_factory;
std::shared_ptr<RKCameraHal> cam_dev;
std::shared_ptr<DisplayProcess> display_process;
std::shared_ptr<FaceProcess> face_process;
std::shared_ptr<H264Encoder> encode_process;
};
static RKVideo* rkvideo = NULL;
static int init_ok = 0;
RKVideo::RKVideo()
{
display_state_ = 0;
face_state_ = false;
h264enc_state_ = false;
memset(&cam_info, 0, sizeof(cam_info));
CamHwItf::getCameraInfos(&cam_info);
if (cam_info.num_camers <= 0) {
printf("[rv_video:%s]fail\n",__func__);
return ;
}
shared_ptr<CamHwItf> new_dev = cam_factory.GetCamHwItf(&cam_info, 0);
cam_dev = ((shared_ptr<RKCameraHal>)
new RKCameraHal(new_dev, cam_info.cam[0]->index, cam_info.cam[0]->type));
cam_dev->init(1280, 720, 25);
ptr_allocator = shared_ptr<RKCameraBufferAllocator>(new RKCameraBufferAllocator());
cam_dev->start(5, ptr_allocator);
display_process = std::make_shared<DisplayProcess>();
if (display_process.get() == nullptr)
std::cout << "[rv_video]DisplayProcess make_shared error" << std::endl;
face_process = std::make_shared<FaceProcess>();
if (face_process.get() == nullptr)
std::cout << "[rv_video]FaceProcess make_shared error" << std::endl;
encode_process = std::make_shared<H264Encoder>();
if (encode_process.get() == nullptr)
std::cout << "[rv_video]H264Encoder make_shared error" << std::endl;
init_ok = 1;
}
RKVideo::~RKVideo()
{
disconnect(cam_dev->mpath(), display_process);
disconnect(cam_dev->mpath(), encode_process);
disconnect(cam_dev->mpath(), face_process);
if (cam_dev)
cam_dev->stop();
cam_dev = NULL;
ptr_allocator = NULL;
display_process = NULL;
face_process = NULL;
encode_process = NULL;
init_ok = 0;
}
int RKVideo::connect(std::shared_ptr<CamHwItf::PathBase> mpath,
std::shared_ptr<StreamPUBase> next,
frm_info_t& frmFmt, const uint32_t num,
std::shared_ptr<RKCameraBufferAllocator> allocator)
{
if (!mpath.get() || !next.get()) {
printf("[rv_video:%s]PathBase,PU is NULL\n",__func__);
}
mpath->addBufferNotifier(next.get());
next->prepare(frmFmt, num, allocator);
if (!next->start()) {
printf("[rv_video:%s]PathBase,PU start failed!\n",__func__);
}
return 0;
}
void RKVideo::disconnect(std::shared_ptr<CamHwItf::PathBase> mpath,
std::shared_ptr<StreamPUBase> next)
{
if (!mpath.get() || !next.get()) {
printf("[rv_video:%s]PathBase,PU is NULL\n",__func__);
return;
}
mpath->removeBufferNotifer(next.get());
next->stop();
next->releaseBuffers();
}
void RKVideo::displayLocal(void)
{
if (cam_info.num_camers <= 0)
return;
if (display_state_ != 1) {
display_state_ = 1;
display_process->showLocalVideo();
connect(cam_dev->mpath(), display_process, cam_dev->format(), 0, nullptr);
}
}
void RKVideo::displayPeer(int w,int h,void* decCallback)
{
if (cam_info.num_camers <= 0)
return;
if (display_state_ != 2) {
display_state_ = 2;
disconnect(cam_dev->mpath(), display_process);
display_process->showPeerVideo(w,h,(DecCallbackFunc)decCallback);
}
}
void RKVideo::displayOff(void)
{
if (cam_info.num_camers <= 0)
return;
if (display_state_ != 0) {
display_state_ = 0;
disconnect(cam_dev->mpath(), display_process);
display_process->setVideoBlack();
}
}
void RKVideo::faceOnOff(bool type)
{
if (cam_info.num_camers <= 0)
return;
if (type == true) {
if (face_state_ == false) {
face_state_ = true;
face_process->faceInit();
connect(cam_dev->mpath(), face_process, cam_dev->format(), 0, nullptr);
}
} else {
if (face_state_ == true) {
face_state_ = false;
disconnect(cam_dev->mpath(), face_process);
face_process->faceUnInit();
}
}
}
void RKVideo::h264EncOnOff(bool type,int w,int h,EncCallbackFunc encCallback)
{
if (cam_info.num_camers <= 0)
return;
if (type == true) {
if (h264enc_state_ == false) {
h264enc_state_ = true;
connect(cam_dev->mpath(), encode_process, cam_dev->format(), 1, ptr_allocator);
encode_process->startEnc(w,h,encCallback);
}
} else {
if (h264enc_state_ == true) {
h264enc_state_ = false;
encode_process->stopEnc();
disconnect(cam_dev->mpath(), encode_process);
}
}
}
void RKVideo::capture(char *file_name)
{
if (display_state_ == 0)
return;
if (h264enc_state_ == true) {
encode_process->capture(file_name);
} else {
display_process->capture(file_name);
}
}
void RKVideo::recordStart(int w,int h,EncCallbackFunc recordCallback)
{
if (display_state_ != 1)
return ;
h264EncOnOff(true,w,h,NULL);
encode_process->recordStart(recordCallback);
}
void RKVideo::recordSetStopFunc(RecordStopCallbackFunc recordStopCallback)
{
encode_process->recordSetStopFunc(recordStopCallback);
}
void RKVideo::recordStop(void)
{
encode_process->recordStop();
// h264EncOnOff(false,0,0,NULL);
}
int RKVideo::getCammerState(void)
{
if (display_process)
return display_process->getCammerState();
else
return 0;
// h264EncOnOff(false,0,0,NULL);
}
static void* threadVideoMonitor(void *arg)
{
while (1) {
sleep(3);
// 如果初始化没找到摄像头,则退出视频处理
if (init_ok == 0)
break;
if (rkvideo) {
// 中途摄像头数据出错的话,直接关机
if (rkvideo->getCammerState() == 0) {
cammerErrorToPowerOff();
break;
// RKVideo* rkvideo_tmp = rkvideo;
// rkvideo = NULL;
// delete rkvideo_tmp;
// sleep(1);
// rkvideo = new RKVideo();
}
}
}
return NULL;
}
static void *threadVideoMsgDeal(void *arg)
{
while (!rkvideo) {
usleep(10000);
}
struct StVideoServer queue_data;
while (1) {
if (queue) {
queue->get(queue,&queue_data);
} else {
sleep(1);
continue;
}
switch(queue_data.msg)
{
case MSG_DISPLAY_LOCAL:
rkvideo->displayLocal();
break;
case MSG_DISPLAY_PEER:
rkvideo->displayPeer(queue_data.w,queue_data.h,(void *)queue_data.p_data_addr);
break;
case MSG_DISPLAY_OFF:
rkvideo->displayOff();
break;
default:
break;
}
}
return NULL;
}
extern "C"
int rkVideoInit(void)
{
rkvideo = new RKVideo();
createThread(threadVideoMonitor,NULL);
createThread(threadVideoMsgDeal,NULL);
}
extern "C"
int rkVideoDisplayLocal(void)
{
struct StVideoServer queue_data;
if (!queue) {
queue = queueCreate("v_server",QUEUE_BLOCK,sizeof(queue_data));
}
queue_data.msg = MSG_DISPLAY_LOCAL;
queue->post(queue,&queue_data);
}
extern "C"
int rkVideoDisplayPeer(int w,int h,void * decCallBack)
{
struct StVideoServer queue_data;
if (!queue) {
queue = queueCreate("v_server",QUEUE_BLOCK,sizeof(queue_data));
}
queue_data.msg = MSG_DISPLAY_PEER;
queue_data.p_data_addr = (long)decCallBack;
queue_data.w = w;
queue_data.h = h;
queue->post(queue,&queue_data);
}
extern "C"
int rkVideoDisplayOff(void)
{
struct StVideoServer queue_data;
if (!queue) {
queue = queueCreate("v_server",QUEUE_BLOCK,sizeof(queue_data));
}
queue_data.msg = MSG_DISPLAY_OFF;
queue->post(queue,&queue_data);
}
extern "C"
int rkVideoFaceOnOff(int type)
{
if (rkvideo == NULL)
return 0;
if (type)
rkvideo->faceOnOff(true);
else
rkvideo->faceOnOff(false);
}
extern "C"
int rkH264EncOn(int w,int h,EncCallbackFunc encCallback)
{
if (rkvideo)
rkvideo->h264EncOnOff(true,w,h,encCallback);
}
extern "C"
int rkH264EncOff(void)
{
if (rkvideo)
rkvideo->h264EncOnOff(false,0,0,NULL);
}
extern "C"
int rkVideoCapture(char *file_name)
{
if (rkvideo)
rkvideo->capture(file_name);
}
extern "C"
int rkVideoRecordStart(int w,int h,EncCallbackFunc recordCallback)
{
if (rkvideo)
rkvideo->recordStart(w,h,recordCallback);
}
extern "C"
int rkVideoRecordSetStopFunc(RecordStopCallbackFunc recordCallback)
{
if (rkvideo)
rkvideo->recordSetStopFunc(recordCallback);
}
extern "C"
int rkVideoRecordStop(void)
{
if (rkvideo)
rkvideo->recordStop();
}
extern "C"
int rkGetVideoRun(void)
{
if (!rkvideo)
return 0;
rkvideo->getCammerState();
}
<file_sep>/src/app/sensor_detector.c
/*
* =============================================================================
*
* Filename: sensor_detector.c
*
* Description: 传感器检测
*
* Version: 1.0
* Created: 2019-07-06 15:47:47
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "hal_sensor.h"
#include "hal_battery.h"
#include "thread_helper.h"
#include "sensor_detector.h"
#include "externfunc.h"
#include "sql_handle.h"
#include "protocol.h"
#include "my_video.h"
#include "my_gpio.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
Sensors *sensor;
static void* theadProximity(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
int state = HAL_SENSER_ERR;
int state_old = HAL_SENSER_ERR;
halSensorInit();
while (1) {
state = halSensorGetState();
if (state != state_old) {
if (state == HAL_SENSOR_INACTIVE) {
printf("out 50cm\n");
} else {
printf("in 50cm\n");
}
}
state_old = state;
usleep(200000);
};
return NULL;
}
static void* theadEle(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
int power_old = 0;
int power_state_old = 0;
int report_low_power = 0; // 发送低电量报警
while (1) {
// 更新充电状态
int power_state = halBatteryGetState();
if (power_state_old != power_state) {
power_state_old = power_state;
if (power_state) {
gpioChargeState(1);
} else {
gpioChargeState(0);
report_low_power = 0;
}
if (sensor->interface->uiUpadteEleState)
sensor->interface->uiUpadteEleState(power_state);
}
// 更新电量
int power = halBatteryGetEle();
// 电量为0且非充电状态
if (power == 0 && power_state == BATTERY_NORMAL) {
if (sensor->interface->uiLowPowerToPowerOff) {
sensor->interface->uiLowPowerToPowerOff();
break;
}
}
if (power_old == 0 || power_old != power) {
power_old = power;
if (sensor->interface->uiUpadteElePower)
sensor->interface->uiUpadteElePower(power);
}
if (power < 20) {
if ( power_state == BATTERY_NORMAL
&& report_low_power == 0) {
report_low_power = 1;
ReportAlarmData alarm_data;
alarm_data.type = ALARM_TYPE_LOWPOWER;
getDate(alarm_data.date,sizeof(alarm_data.date));
sqlInsertRecordAlarm(alarm_data.date,alarm_data.type,0,0,0,0);
protocol_hardcloud->reportAlarm(&alarm_data);
gpioLowPowerState(1);
}
} else {
report_low_power = 0;
gpioLowPowerState(0);
}
sleep(1);
}
return NULL;
}
static int getElePower(void)
{
return halBatteryGetEle();
}
static int getEleState(void)
{
return halBatteryGetState();
}
void sensorDetectorInit(void)
{
sensor = (Sensors *) calloc(1,sizeof(Sensors ));
sensor->interface = (SensorsInterface *) calloc(1,sizeof(SensorsInterface));
sensor->getElePower = getElePower;
sensor->getEleState = getEleState;
createThread(theadProximity,NULL);
createThread(theadEle,NULL);
}
<file_sep>/module/stdioredirect/stdioredirect.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define CONSOLE_PATH "/tmp/consolename"
int main()
{
char *tty = ttyname(1);
int fd;
char name[64]={0};
printf("tty %s \n", tty);
fd = open(CONSOLE_PATH, O_RDWR | O_CREAT | O_TRUNC);
if (fd >= 0) {
sprintf(name, "%s", tty);
write(fd, name, strlen(name) + 1);
close(fd);
fflush(NULL);
} else {
printf("open faild \n");
}
return 0;
}
<file_sep>/src/app/video/h264_enc_dec/mpp_dec_test.cpp
/*
* Copyright (C) 2017 <NAME> <EMAIL>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see http://www.gnu.org/licenses
*
* Any non-GPL usage of this software or parts of this software is strictly
* forbidden.
*
*/
#ifdef NDEBUG
#undef NDEBUG
#endif
#ifndef DEBUG
#define DEBUG
#endif
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <easymedia/buffer.h>
#include <easymedia/key_string.h>
#include <easymedia/media_config.h>
#include <easymedia/utils.h>
#include <easymedia/decoder.h>
#include "mpi_dec_api.h"
struct SpsPpsTemp {
char buf[64];
int size;
};
extern "C" {
int split_h264_separate(const uint8_t *buffer, size_t length,int *sps_length,int *pps_length) ;
}
static std::shared_ptr<easymedia::VideoDecoder> g_mpp_dec;
static struct SpsPpsTemp sps_pps_tmp;
static char h264_sps_pps[64];
static std::string param;
static std::string mpp_codec = "rkmpp";
static void dump_output(const std::shared_ptr<easymedia::MediaBuffer> &out,int *out_size,unsigned char *out_data,int *out_w,int *out_h)
{
auto out_image = std::static_pointer_cast<easymedia::ImageBuffer>(out);
// hardware always need aligh width/height, we write the whole buffer with
// virtual region which may contains invalid data
// printf("out:%d\n",out_image->GetValidSize() );
if (out_image->GetValidSize() <= 0)
return;
const ImageInfo &info = out_image->GetImageInfo();
// fprintf(stderr, "got one frame, format: %s <%dx%d>in<%dx%d>\n",
// PixFmtToString(info.pix_fmt), info.width, info.height,
// info.vir_width, info.vir_height);
*out_size = CalPixFmtSize(out_image->GetPixelFormat(), out_image->GetVirWidth(),
out_image->GetVirHeight());
*out_w = info.vir_width;
*out_h = info.vir_height;
if (*out_size)
memcpy(out_data,out_image->GetPtr(),*out_size);
}
static bool get_output_and_process(easymedia::VideoDecoder *mpp_dec,int *out_size,unsigned char *out_data,int *out_w,int *out_h)
{
auto out_buffer = mpp_dec->FetchOutput();
if (!out_buffer && errno != 0) {
fprintf(stderr, "fatal error %m\n");
return false;
}
if (out_buffer && !out_buffer->IsValid() && !out_buffer->IsEOF()) {
// got a image info buffer
// fprintf(stderr, "got info frame\n");
// fetch the real frame
out_buffer = mpp_dec->FetchOutput();
}
if (out_buffer) {
dump_output(std::static_pointer_cast<easymedia::ImageBuffer>(out_buffer),out_size,out_data,out_w,out_h);
}
return true;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief mpiH264Decode h264视频解码,由于云之讯传过来的视频格式问题,需要过滤
* 0x00 0x00 0x00 0x00 0x01 0x06 0x05这个非视频信息
* 而云之讯传视频sps和pps时,会将这hal分开传输,先传sps,再传pps,再传i帧数据
* 需要自己组合
*
* @param This
* @param in_data
* @param in_size
* @param out_data
* @param out_w
* @param out_h
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int mpiH264Decode(H264Decode *This,unsigned char *in_data,int in_size,unsigned char *out_data,int *out_w,int *out_h)
{
int sps_length = 0,pps_length = 0;
unsigned char *i_frame = NULL;
unsigned char *frame = in_data;
int frame_size = in_size;
// 过滤非视频信息
if (in_data[0] == 0 && in_data[1] == 0 && in_data[2] == 0 && in_data[3] == 1
&& in_data[4] == 0x6 && in_data[5] == 0x5) {
return 0;
}
// 判断是否是sps或pps,若是则添加到缓存中
int frame_type = split_h264_separate(in_data,in_size,&sps_length,&pps_length);
if (frame_type == 7 || frame_type == 8) {
if (frame_type == 7) {
if (memcmp(h264_sps_pps,in_data,sps_length)) {
my_h264dec->unInit(my_h264dec);
my_h264dec->init(my_h264dec,1024,600);
memcpy(h264_sps_pps,in_data,sps_length);
}
memset(&sps_pps_tmp,0,sizeof(sps_pps_tmp));
}
if (sps_pps_tmp.size >= 0) {
memcpy(&sps_pps_tmp.buf[sps_pps_tmp.size],in_data,in_size);
sps_pps_tmp.size += in_size;
}
return 0;
}
// 非sps和pps时,重新组包组合成sps+pps+i帧
if (sps_pps_tmp.size > 0) {
i_frame = (unsigned char *) calloc(1,in_size + sps_pps_tmp.size);
memcpy(i_frame,sps_pps_tmp.buf,sps_pps_tmp.size);
memcpy(i_frame + sps_pps_tmp.size,in_data,in_size);
frame = i_frame;
frame_size += sps_pps_tmp.size;
}
// printf("size:%d\n",frame_size );
memset(&sps_pps_tmp,0,sizeof(sps_pps_tmp));
std::shared_ptr<easymedia::MediaBuffer> buffer;
buffer = easymedia::MediaBuffer::Alloc(frame_size);
assert(buffer);
memcpy(buffer->GetPtr(),frame,frame_size);
buffer->SetValidSize(frame_size);
buffer->SetUSTimeStamp(easymedia::gettimeofday());
int ret = g_mpp_dec->SendInput(buffer);
get_output_and_process(g_mpp_dec.get(),&ret,out_data,out_w,out_h);
if (i_frame)
free(i_frame);
return ret;
}
static int mpiH264DecInit(H264Decode *This,int width,int height)
{
printf("[%s]\n", __func__);
g_mpp_dec = easymedia::REFLECTOR(Decoder)::Create<easymedia::VideoDecoder>(
mpp_codec.c_str(), param.c_str());
if (!g_mpp_dec) {
fprintf(stderr, "Create decoder %s failed\n", mpp_codec.c_str());
return -1;
}
return 0;
}
static int mpiH264DecUnInit(H264Decode *This)
{
printf("[%s]\n", __func__);
g_mpp_dec = NULL;
memset(h264_sps_pps,0,sizeof(h264_sps_pps));
return 0;
}
#if 1
void myH264DecInit(void)
{
int split_mode = 0;//= input_dir_path.empty() ? 1 : 0;
int timeout = -1;
my_h264dec = (H264Decode *)calloc(1,sizeof(H264Decode));
my_h264dec->init = mpiH264DecInit;
my_h264dec->unInit = mpiH264DecUnInit;
my_h264dec->decode = mpiH264Decode;
PARAM_STRING_APPEND(param, KEY_INPUTDATATYPE, VIDEO_H264);
// PARAM_STRING_APPEND_TO(param, KEY_MPP_GROUP_MAX_FRAMES, 4);
PARAM_STRING_APPEND_TO(param, KEY_MPP_SPLIT_MODE, split_mode);
PARAM_STRING_APPEND_TO(param, KEY_OUTPUT_TIMEOUT, timeout);
easymedia::REFLECTOR(Decoder)::DumpFactories();
}
#endif
<file_sep>/src/gui/my_controls/my_static.h
/*
* =============================================================================
*
* Filename: my_static.h
*
* Description: 自定义静态控件
*
* Version: 1.0
* Created: 2019-04-23 19:46:14
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_STATIC_H
#define _MY_STATIC_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include "my_controls.h"
#include "commongdi.h"
#define CTRL_MYSTATIC ("mystatic")
enum {
MSG_MYSTATIC_SET_TITLE = MSG_USER + 1,
};
enum { // 控件类型
MYSTATIC_TYPE_TEXT,
MYSTATIC_TYPE_TEXT_ONLY,
MYSTATIC_TYPE_TEXT_AND_IMG,
MYSTATIC_TYPE_IMG_ONLY,
};
typedef struct {
char text[64]; // 文字
PLOGFONT font; // 字体
int font_color; // 文字颜色
int bkg_color; // 背景颜色
int flag; // 类型
BITMAP *image; // 图片
}MyStaticCtrlInfo;
typedef struct _MyCtrlStatic{
HWND idc; // 控件ID
int flag; // 类型
int16_t x,y,w,h;
const char *text; // 文字
int font_color; // 文字颜色
int bkg_color; // 背景颜色
char *img_name; // 常态图片名字,不带扩展名,完整路径由循环赋值
PLOGFONT font; // 字体
BITMAP image; // 正常状态图片
}MyCtrlStatic;
HWND createMyStatic(HWND hWnd,MyCtrlStatic *);
MyControls *my_static;
void initMyStatic(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/video/process/face_process.h
/*
* =============================================================================
*
* Filename: face_process.h
*
* Description: 人脸识别数据流接口
*
* Version: 1.0
* Created: 2019-06-19 11:51:10
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _FACE_PROCESS_H
#define _FACE_PROCESS_H
#include <CameraHal/StrmPUBase.h>
class FaceProcess : public StreamPUBase {
public:
FaceProcess();
virtual ~FaceProcess();
bool processFrame(std::shared_ptr<BufferBase> input,
std::shared_ptr<BufferBase> output) override;
bool start_enc(void) const {
return start_enc_;
};
void faceInit(void);
void faceUnInit(void);
int faceRegist(void *data);
private:
bool start_enc_;
};
#endif
<file_sep>/src/app/protocol.c
/*
* =============================================================================
*
* Filename: protocol.c
*
* Description: 猫眼相关协议
*
* Version: 1.0
* Created: 2019-05-18 13:53:49
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "my_http.h"
#include "my_mqtt.h"
#include "my_update.h"
#include "json_dec.h"
#include "udp_server.h"
#include "tcp_client.h"
#include "thread_helper.h"
#include "externfunc.h"
#include "protocol.h"
#include "qrenc.h"
#include "my_video.h"
#include "my_face.h"
#include "config.h"
#include "timer.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
void registHardCloud(void);
void registTalk(void);
void registSingleChip(void);
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
enum {
TP_CALL, //呼叫对讲
TP_TESTROUTE=0x200, //路由环回测试命令,类似于PING命令的作用
TP_NATBURROW, //NAT路由器穿透命令
TP_RTPBURROW, //RTP音视频穿透命令
TP_DEVCHECK, //设备测试
TP_UPDATEPROC, //程序更新通知
TP_UPDATEEND, //返回数据服务中心更新完成的消息
TP_GETAPPVERSION, //取程序版本号
TP_ELEVATOR, //电梯联动
TP_UPDATEMSG, //服务器IP更新信息,房号配置表更换信息
TP_GETREMOTEPWD, //获取设置服务器远程密码
TP_SETREMOTEPWD, //获取设置服务器远程密码
TP_SENDMACTOSRV, //发送MAC地址,IP地址及房号信息到服务器
TP_CHANGEROOMID, //更改房号
TP_TRANCMDBYSRV, //通过服务器转发包
TP_TRANSRTP, //发送RTP包
TP_TRANSELECTRIC, //转发送电器控制包
TP_SENDSOFTVER, //发送本设备版本信息
TP_RETUPDATEMSG, //返回升级信息 0x211
TP_BUTTONALARM, //紧急按钮报警
TP_LOCALDEVID, //获取本机唯一编号
TP_ADVERTISEMENT, //中控机接收远程广告发布, 为了向U9中控机兼容,才更改值
TP_LOCALHARDCODE = 0x520, //获取本机硬件码
TP_REQ_AUTHENTICATION = 0x600, //获取人脸识别license
TP_RETURN_AUTHENTICATION = 0x601, //回复人脸识别license
TP_CONFIRM_AUTHENTICATION = 0x602, // 应答回复人脸识别license
};
enum
{
REQSERVERINF, // 终端向服务器申请 ID 命令号
RESPONSESERVERINF // 服务器向终端返回 ID 命令号
};
enum {
TYPE_CENTER, //管理中心
TYPE_DOOR, //门口机
TYPE_XC, //保留
TYPE_USER, //中控主机
TYPE_REMOTE, //基于PC上的呼叫程序,如网站的对讲程序
TYPE_XCDOOR, //保留
TYPE_FDOOR, //户门口机
TYPE_ZNBOX, //智能箱
TYPE_NETRF, //网络RF模块
TYPE_DEVID_SRV=0x100, //取设备ID服务器
TYPE_DEVHARDCODE_SRV=0x101, //取设备硬件码服务器
TYPE_SINGLECHIP = 0x120, //单片机设备
TYPE_ALL=0xFFFFFFFF //所有设备
};
//搜索设备信息包定义
enum {
CMD_GETSTATUS, //读设备信息
CMD_RETSTATUS //返回设备信息
};
/* 包头 */
typedef struct
{
unsigned int ID;
unsigned int Size;
unsigned int Type;
}COMMUNICATION;
typedef struct
{
unsigned int ID; //包头ID号
unsigned int Size; //包大小
unsigned int Type; //包类型
unsigned int Cmd; //命令
unsigned int ReqType; //请求信息设备类型
unsigned long long int DevID; //设备ID
char Addition[32]; //附加信息
} TResDeviceInf;
typedef struct
{
unsigned int ID; //包头ID号
unsigned int Size; //包大小
unsigned int Type; //包类型,必须为TP_DEVCHECK
unsigned int Cmd; //命令,必须为CMD_GETSTATUS
unsigned int DevType; //设备类型
char Addition[20]; //附加信息
} TGetDeviceInfo;
//返回设备信息包定义
typedef struct
{
unsigned int ID; //包头ID号
unsigned int Size; //包大小
unsigned int Type; //包类型,必须为TP_DEVCHECK
unsigned int Cmd; //命令,必须为CMD_RETSTATUS
unsigned int DevType; //设备类型(以数值方式描述)
char Code[16]; //设备虚拟编号
char Name[32]; //设备名称
char IP[16]; //设备IP地址
char dType[20]; //设备类型(以字符方式描述)
char IMEI[24]; //设备机身号
char Addition[20]; //附加信息
} TRetDeviceInfo;
typedef struct
{
char ip[64]; //升级的文件
char file[256]; //提示信息
} TUpdateRevertFile;
#pragma pack (1)
typedef struct
{
unsigned int ID; //包头ID号
unsigned int Size; //包大小
unsigned int Type; //包类型,必须为TP_DEVCHECK
unsigned int Cmd; //命令,必须为CMD_GETSTATUS
char reserve;
unsigned long long int HardCode; //硬件码
char Addition[20]; //附加信息
} TGetDeviceBodyCode; //获取设备机身码使用
#pragma pack ()
typedef struct
{
unsigned int ID; //包头ID号
unsigned int Size; //包大小
unsigned int Type; //包类型
unsigned int Cmd; //命令 主动请求=0, 被动响应=1
unsigned int DevType; //设备类型, TYPE_DEVID_SRV=0x100,
unsigned int CheckSum; //校验码 = StrHardCode + StrKey
char StrHardCode[256]; //硬件码
char StrKey[512]; //Key
} TRSCertification;
typedef struct _PacketsID {
char IP[16];
uint32_t id;
uint64_t dwTick; //时间
}PacketsID;
typedef struct _UdpCmdRead {
unsigned int cmd;
void (*udpCmdProc)( struct _SocketHandle *ABinding,
struct _SocketPacket *AData); //协议处理
}UdpCmdRead;
typedef struct _ProtocolPriv {
}ProtocolPriv;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
Protocol *protocol;
static unsigned int packet_id;
static int get_imei_end = 1;
static int get_face_end = 1;
static Timer *timer_protocol_1s = NULL; // 协议1s定时器
static Timer *timer_getimei_5s = NULL; // 获取机身码5s定时器
static Timer *timer_getface_5s = NULL; // 获取人脸license 5s定时器
static void (*getImeiCallback)(int result); // 机身码获取回调函数
static void (*getFaceCallback)(int result); // 人脸license获取回调函数
IpcServer* ipc_main = NULL;
static unsigned long long htonll(unsigned long long val)
{
#if 1
if (__BYTE_ORDER == __LITTLE_ENDIAN)
{
return (((unsigned long long)htonl((int)((val << 32) >> 32))) << 32) | (unsigned int)htonl((int)(val >> 32));
}
else if (__BYTE_ORDER == __BIG_ENDIAN)
{
return val;
}
#endif
}
static void udpLocalGetIMEI(SocketHandle *ABinding,SocketPacket *AData)
{
if(AData->Size != sizeof(TResDeviceInf)) {
return;
}
TResDeviceInf *GetPacket = (TResDeviceInf*)AData->Data;
if(GetPacket->Cmd == RESPONSESERVERINF && GetPacket->ReqType==TYPE_DEVID_SRV) {
get_imei_end = 1;
printf("[%s]imei:%llX\n",__func__,htonll(GetPacket->DevID));
sprintf(g_config.imei,"%llX",htonll(GetPacket->DevID));
}
}
static void udpLocalGetHardCode(SocketHandle *ABinding,SocketPacket *AData)
{
if(AData->Size != sizeof(TResDeviceInf)) {
return;
}
TResDeviceInf *GetPacket = (TResDeviceInf*)AData->Data;
if(GetPacket->Cmd == RESPONSESERVERINF && GetPacket->ReqType==TYPE_DEVHARDCODE_SRV) {
get_imei_end = 1;
printf("[%s]hardcode:%llx\n",__func__,GetPacket->DevID);
sprintf(g_config.hardcode,"%llx",GetPacket->DevID);
}
}
static void udpLocalgetMsg(SocketHandle *ABinding,SocketPacket *AData)
{
printf("TP_DEVCHECK:LocalMsgGetProc():%s\n",ABinding->IP);
if(AData->Size==sizeof(TGetDeviceInfo)) {
printf("MsgGetProc():TGetDeviceInfo\n");
//返回本机设备信息
TGetDeviceInfo *GetDevMsg = (TGetDeviceInfo*)AData->Data;
printf("GetDevMsg DevType:%d\n", GetDevMsg->DevType);
if(GetDevMsg->Cmd==CMD_GETSTATUS &&
(GetDevMsg->DevType==TYPE_DOOR || GetDevMsg->DevType==0xFFFFFFFF)) { //类型为中控主机或所有设备
TRetDeviceInfo RetDevMsg;
const char *pDestIP;
memset(&RetDevMsg,0,sizeof(TRetDeviceInfo));
RetDevMsg.ID = packet_id++;
RetDevMsg.Size = sizeof(TRetDeviceInfo);
RetDevMsg.Type = TP_DEVCHECK;
RetDevMsg.Cmd = CMD_RETSTATUS; //返回设备信息
RetDevMsg.DevType = TYPE_DOOR;
// strcpy(RetDevMsg.IP,Public.cLocalIP); //IP
strcpy(RetDevMsg.Name,"cat eye");
strcpy(RetDevMsg.dType,"cat eye"); //类型
sprintf(RetDevMsg.IMEI,"%s",g_config.imei); //设备唯一编号
sprintf(RetDevMsg.Addition,"%s-%s-%s",DEVICE_SVERSION,g_config.k_version,g_config.s_version);
udp_server->SendBuffer(udp_server,"255.255.255.255",ABinding->Port, //返回信息
(char *)&RetDevMsg,sizeof(TRetDeviceInfo));
}
} else if(AData->Size==sizeof(TRetDeviceInfo)) {
TRetDeviceInfo *pDevMsg = (TRetDeviceInfo*)AData->Data;
if(pDevMsg->Cmd != CMD_RETSTATUS) {
return;
}
if(pDevMsg->DevType != TYPE_DEVID_SRV) {
return;
}
//获取设备唯一编号
// if(get_imei_end == 1) {
// return;
// }
// get_imei_end = 1;
TResDeviceInf Packet;
memset(&Packet,0,sizeof(TResDeviceInf));
Packet.ID = packet_id++;
Packet.Size = sizeof(TResDeviceInf);
Packet.Type = TP_LOCALDEVID;
Packet.Cmd = REQSERVERINF;
Packet.ReqType = TYPE_DOOR;
udp_server->AddTask(udp_server,
ABinding->IP,ABinding->Port,&Packet,Packet.Size,5,NULL,NULL);
printf("Get Local ID From %s\n",ABinding->IP);
}
}
static void udpUpdateProc(SocketHandle *ABinding,SocketPacket *AData)
{
printf("TP_RETUPDATEMSG:UpdateProc()\n");
TUpdateRevertFile *cBuf = NULL;
char *Packet = (char *)&AData->Data[sizeof(COMMUNICATION)];
cBuf = (TUpdateRevertFile *)malloc(sizeof(TUpdateRevertFile));
sprintf(cBuf->ip,"%s",ABinding->IP);
sprintf(cBuf->file,"%s",Packet);
if (my_video)
my_video->update(UPDATE_TYPE_CENTER,ABinding->IP,0,Packet);
if (cBuf)
free(cBuf);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief getFaceLicenseRespones 人脸识别获取成功后回复
*
* @param ABinding
*/
/* ---------------------------------------------------------------------------*/
static void getFaceLicenseRespones(SocketHandle *ABinding)
{
TRSCertification Packet;
memset(&Packet,0,sizeof(TRSCertification));
Packet.ID = packet_id++;
Packet.Size = sizeof(TRSCertification);
Packet.Type = TP_CONFIRM_AUTHENTICATION;
Packet.Cmd = 0;
Packet.DevType = TYPE_DEVID_SRV;
strcpy(Packet.StrHardCode,g_config.hardcode);
strcpy(Packet.StrKey,"Certification is OK");
unsigned long i;
for (i=0; i<strlen(Packet.StrHardCode); i++)
Packet.CheckSum += Packet.StrHardCode[i];
for (i=0; i<strlen(Packet.StrKey); i++)
Packet.CheckSum += Packet.StrKey[i];
if(udp_server)
udp_server->AddTask(udp_server,
ABinding->IP, 7800, &Packet, Packet.Size, 5,NULL,NULL);
}
static void udpGetFaceLicense(SocketHandle *ABinding,SocketPacket *AData)
{
if(AData->Size != sizeof(TRSCertification))
return;
TRSCertification *GetPacket = (TRSCertification*)AData->Data;
if (GetPacket->Cmd != 1)
return;
if(strcmp(GetPacket->StrHardCode,g_config.hardcode))
return;
unsigned long i;
unsigned int checksum = 0;
for (i=0; i<strlen(GetPacket->StrHardCode); i++)
checksum += GetPacket->StrHardCode[i];
for (i=0; i<strlen(GetPacket->StrKey); i++)
checksum += GetPacket->StrKey[i];
if (checksum != GetPacket->CheckSum)
return;
if (my_face) {
// 获取人脸识别后初始化人脸,看是否成功
strcpy(g_config.f_license,GetPacket->StrKey);
g_config.face_enable = 1;
if (my_face->init() == -1) {
strcpy(g_config.f_license,"0");
} else {
getFaceLicenseRespones(ABinding);
get_face_end = 1;
ConfigSavePrivate();
}
}
printf("[%s]face_license:%s\n",__func__,g_config.f_license);
}
static void getIMEIFromTools(void)
{
if (strlen(g_config.hardcode) < 2)
return;
TGetDeviceBodyCode Packet;
memset(&Packet,0,sizeof(TGetDeviceBodyCode));
Packet.ID = packet_id++;
Packet.Size = sizeof(TGetDeviceBodyCode);
Packet.Type = TP_LOCALDEVID;
Packet.Cmd = CMD_GETSTATUS;
Packet.HardCode = htonll((unsigned long long)strtoull(g_config.hardcode, NULL, 16));
printf("%s(),hardcode:%s\n",__func__,g_config.hardcode);
if(udp_server)
udp_server->AddTask(udp_server,
"255.255.255.255", 7801, &Packet, Packet.Size, 5,NULL,NULL);
}
static void getFaceLicenseFromTools(void)
{
TRSCertification Packet;
memset(&Packet,0,sizeof(TRSCertification));
Packet.ID = packet_id++;
Packet.Size = sizeof(TRSCertification);
Packet.Type = TP_REQ_AUTHENTICATION;
Packet.Cmd = 0;
Packet.DevType = TYPE_DEVID_SRV;
strcpy(Packet.StrHardCode,g_config.hardcode);
strcpy(Packet.StrKey,my_face->getDeviceKey());
unsigned long i;
for (i=0; i<strlen(Packet.StrHardCode); i++)
Packet.CheckSum += Packet.StrHardCode[i];
for (i=0; i<strlen(Packet.StrKey); i++)
Packet.CheckSum += Packet.StrKey[i];
if(udp_server)
udp_server->AddTask(udp_server,
"255.255.255.255",
7800, &Packet, Packet.Size, 5,NULL,NULL);
}
static void getHardCode(void)
{
TGetDeviceBodyCode Packet;
memset(&Packet,0,sizeof(TGetDeviceBodyCode));
Packet.ID = packet_id++;
Packet.Size = sizeof(TGetDeviceBodyCode);
Packet.Type = TP_LOCALHARDCODE;
Packet.Cmd = CMD_GETSTATUS;
if(udp_server)
udp_server->AddTask(udp_server,
"255.255.255.255",
7801, &Packet, Packet.Size, 5,NULL,NULL);
}
static void timerImei5sThread(void *arg)
{
int *get_type = (int *)arg;
timer_getimei_5s->stop(timer_getimei_5s);
if (get_imei_end == 0) {
if (getImeiCallback)
getImeiCallback(0);
return;
}
get_imei_end = 0;
if (*get_type == 0) {
*get_type = 1;
getIMEIFromTools();
timer_getimei_5s->start(timer_getimei_5s);
} else {
char buf[128] = {0};
sprintf(buf,"%s/%s",g_config.imei,g_config.hardcode);
qrcodeString(buf,QRCODE_IMIE);
if (getImeiCallback)
getImeiCallback(1);
ConfigSavePrivate();
}
}
static void getImei(void (*callBack)(int result))
{
static int get_type = 0; //获取机身码或者硬件码
if (timer_getimei_5s == NULL)
timer_getimei_5s = timerCreate(TIMER_1S * 5,timerImei5sThread,&get_type);
if (timer_getimei_5s->isStop(timer_getimei_5s) == 0) {
printf("wait for getting end\n");
return;
}
getImeiCallback = callBack;
if (strlen(g_config.hardcode) < 2) {
get_type = 0;
getHardCode();// 获取硬件码
} else {
get_type = 1;
getIMEIFromTools();// 获取机身码
}
timer_getimei_5s->start(timer_getimei_5s);
get_imei_end = 0;
}
static void timerFace5sThread(void *arg)
{
timer_getface_5s->stop(timer_getface_5s);
#if 0
strcpy(g_config.f_license,"045c1ccdafda01ebddd775e620d5635a8294af6ce2435297cff5f019f81442e48b006dfa531cab9a57915eacbacfd1ea5242e58037897259c4fb0367a9a4b1bf");
if (my_face->init() == -1)
strcpy(g_config.f_license,"0");
else
get_face_end = 1;
#endif
if (get_face_end == 0) {
if (getFaceCallback)
getFaceCallback(0);
return;
}
get_face_end = 0;
if (getFaceCallback)
getFaceCallback(1);
ConfigSavePrivate();
}
static void getFaceLicense(void (*callBack)(int result))
{
if (timer_getface_5s == NULL)
timer_getface_5s = timerCreate(TIMER_1S * 5,timerFace5sThread,NULL);
if (timer_getface_5s->isStop(timer_getface_5s) == 0) {
printf("wait for getting end\n");
return;
}
getFaceCallback = callBack;
getFaceLicenseFromTools();
timer_getface_5s->start(timer_getface_5s);
get_face_end = 0;
}
static int isNeedToUpdate(char *version,char *content)
{
return my_update->needUpdate(my_update,version,content);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpKillTaskCondition 根据条件删除任务
*
* @param arg1 udp数据
* @param arg2 传入参数
*
* @returns 删除0失败 1成功
*/
/* ---------------------------------------------------------------------------*/
static int udpKillTaskCondition(void *arg1,void *arg2)
{
int id = *(int *)arg2;
COMMUNICATION * pHead = (COMMUNICATION*)arg1;
if(pHead->ID==id)
return 1;
return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpUdpProtocolFilter 接收协议前过滤重复协议以及应答回复
*
* @param ABinding
* @param AData
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int udpUdpProtocolFilter(SocketHandle *ABinding,SocketPacket *AData)
{
static PacketsID packets_id[10] = {0};
static int packet_pos = 0;
uint64_t dwTick;
int i;
// 收到无效字节
if (AData->Size < 4)
return 0;
// 收到4个字节为对方返回的应答包,即ID
if (AData->Size == 4) {
udp_server->KillTaskCondition(udp_server,
udpKillTaskCondition,AData->Data);
return 0;
}
// 收到无效字节
if (AData->Size < sizeof(COMMUNICATION))
return 0;
// 收到其他协议则回复相同ID
udp_server->SendBuffer(udp_server,ABinding->IP,ABinding->Port,
AData->Data,4);
dwTick = getMs();
// 过滤相同IP发送的多次重复命令
for (i=0; i<10; i++) {
if (strcmp(ABinding->IP,packets_id[i].IP) == 0
&& *(uint32_t*)AData->Data == packets_id[i].id ){
return 0;
}
}
sprintf(packets_id[packet_pos].IP,"%s",ABinding->IP);
packets_id[packet_pos].id = *(uint32_t*)AData->Data;
packets_id[packet_pos++].dwTick = dwTick;
packet_pos %= 10;
return 1;
}
static void udpLocalCall(SocketHandle *ABinding,SocketPacket *AData)
{
if (protocol_talk && protocol_talk->udpCmd)
protocol_talk->udpCmd( ABinding->IP,ABinding->Port,
AData->Data,AData->Size);
}
static UdpCmdRead udp_cmd_handle[] = {
{TP_CALL, udpLocalCall},
{TP_DEVCHECK, udpLocalgetMsg},
{TP_LOCALDEVID, udpLocalGetIMEI},
{TP_LOCALHARDCODE, udpLocalGetHardCode},
{TP_RETUPDATEMSG, udpUpdateProc},
{TP_RETURN_AUTHENTICATION,udpGetFaceLicense},
{0,NULL},
};
static void udpSocketRead(SocketHandle *ABinding,SocketPacket *AData)
{
if (udpUdpProtocolFilter(ABinding,AData) == 0)
return;
COMMUNICATION * head = (COMMUNICATION *)AData->Data;
int i;
for(i=0; udp_cmd_handle[i].udpCmdProc != NULL; i++) {
if (udp_cmd_handle[i].cmd == head->Type) {
if (udp_cmd_handle[i].udpCmdProc)
udp_cmd_handle[i].udpCmdProc(ABinding,AData);
return;
}
}
// printf("[%s]:IP:%s,Cmd=0x%04x\n",__FUNCTION__,ABinding->IP,head->Type);
}
static void ipcCallback(char *data,int size )
{
IpcData ipc_data;
memcpy(&ipc_data,data,sizeof(IpcData));
if (protocol_singlechip)
protocol_singlechip->deal(&ipc_data);
}
void protocolInit(void)
{
packet_id = (unsigned)time(NULL);
udpServerInit(udpSocketRead,7800);
protocol = (Protocol *) calloc(1,sizeof(Protocol));
protocol->priv = (ProtocolPriv *) calloc(1,sizeof(ProtocolPriv));
protocol->getImei = getImei;
protocol->getFaceLicense = getFaceLicense;
protocol->isNeedToUpdate = isNeedToUpdate;
ipc_main = ipcCreate(IPC_MAIN,ipcCallback);
registHardCloud();
registTalk();
registSingleChip();
}
<file_sep>/module/cap/main.cpp
#include <list>
#include "md_camerahal.h"
#include "md_camerabuf.h"
#include "thread_helper.h"
#include "process/md_display_process.h"
#include "protocol.h"
#include "config.h"
class RKVideo {
public:
RKVideo();
~RKVideo();
int connect(std::shared_ptr<CamHwItf::PathBase> mpath,
std::shared_ptr<StreamPUBase> next,
frm_info_t& frmFmt, const uint32_t num,
std::shared_ptr<RKCameraBufferAllocator> allocator);
void disconnect(std::shared_ptr<CamHwItf::PathBase> mpath,
std::shared_ptr<StreamPUBase> next);
void displayLocal(void);
void capture(char *file_name);
private:
int display_state_; // 0关闭 1本地视频 2远程视频
struct rk_cams_dev_info cam_info;
std::shared_ptr<RKCameraBufferAllocator> ptr_allocator;
CameraFactory cam_factory;
std::shared_ptr<RKCameraHal> cam_dev;
std::shared_ptr<DisplayProcess> display_process;
};
static RKVideo* rkvideo = NULL;
static int init_ok = 0;
RKVideo::RKVideo()
{
display_state_ = false;
memset(&cam_info, 0, sizeof(cam_info));
CamHwItf::getCameraInfos(&cam_info);
if (cam_info.num_camers <= 0) {
printf("[rv_video:%s]fail\n",__func__);
return ;
}
shared_ptr<CamHwItf> new_dev = cam_factory.GetCamHwItf(&cam_info, 0);
cam_dev = ((shared_ptr<RKCameraHal>)
new RKCameraHal(new_dev, cam_info.cam[0]->index, cam_info.cam[0]->type));
cam_dev->init(1280, 720, 25);
ptr_allocator = shared_ptr<RKCameraBufferAllocator>(new RKCameraBufferAllocator());
cam_dev->start(4, ptr_allocator);
display_process = std::make_shared<DisplayProcess>();
if (display_process.get() == nullptr)
std::cout << "[rv_video]DisplayProcess make_shared error" << std::endl;
init_ok = 1;
}
RKVideo::~RKVideo()
{
disconnect(cam_dev->mpath(), display_process);
if (cam_dev)
cam_dev->stop();
init_ok = 0;
}
int RKVideo::connect(std::shared_ptr<CamHwItf::PathBase> mpath,
std::shared_ptr<StreamPUBase> next,
frm_info_t& frmFmt, const uint32_t num,
std::shared_ptr<RKCameraBufferAllocator> allocator)
{
if (!mpath.get() || !next.get()) {
printf("[rv_video:%s]PathBase,PU is NULL\n",__func__);
}
mpath->addBufferNotifier(next.get());
next->prepare(frmFmt, num, allocator);
if (!next->start()) {
printf("[rv_video:%s]PathBase,PU start failed!\n",__func__);
}
return 0;
}
void RKVideo::disconnect(std::shared_ptr<CamHwItf::PathBase> mpath,
std::shared_ptr<StreamPUBase> next)
{
if (!mpath.get() || !next.get()) {
printf("[rv_video:%s]PathBase,PU is NULL\n",__func__);
return;
}
mpath->removeBufferNotifer(next.get());
next->stop();
next->releaseBuffers();
}
void RKVideo::displayLocal(void)
{
if (cam_info.num_camers <= 0)
return;
if (display_state_ != 1) {
display_state_ = 1;
connect(cam_dev->mpath(), display_process, cam_dev->format(), 0, nullptr);
}
}
void RKVideo::capture(char *file_name)
{
if (display_state_ == 0)
return;
display_process->capture(file_name);
}
int main(int argc, char *argv[])
{
if (argc < 3)
return 0;
rkvideo = new RKVideo();
rkvideo->displayLocal();
int count = atoi(argv[2]);
char path[64] = {0};
usleep(500000);
for (int i = 0; i < count; ++i) {
sprintf(path,"%s%s_%d.jpg",FAST_PIC_PATH,argv[1],i);
rkvideo->capture(path);
usleep(500000);
printf("cap:%s\n", path);
}
delete rkvideo;
return 0;
}
<file_sep>/src/app/sql_handle.h
/*
* =============================================================================
*
* Filename: sqlHandle.h
*
* Description: 数据库操作接口
*
* Version: 1.0
* Created: 2018-05-21 22:48:57
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _SQL_HANDLE_H
#define _SQL_HANDLE_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <stdint.h>
extern void sqlInsertUserInfoNoBack(
char *user_id,
char *login_token,
char *nick_name,
int type,
int scope);
extern void sqlInsertUserInfo(
char *user_id,
char *login_token,
char *nick_name,
int type,
int scope);
extern int sqlGetUserInfoUseType(
int type,
char *user_id,
char *login_token,
char *nick_name,
int *scope);
extern int sqlGetUserInfoUseUserId(
char *user_id,
char *nick_name,
int *scope);
extern int sqlGetUserInfoStart(int type);
/* ---------------------------------------------------------------------------*/
/**
* @brief sqlGetUserInfoUseScopeStart 根据类型开始获取用户数量
*
* @param scope
*
* @returns -1时获取失败,正在有其他线程操作数据库
*/
/* ---------------------------------------------------------------------------*/
extern int sqlGetUserInfoUseScopeStart(int scope);
extern void sqlGetUserInfosUseScope(
char *user_id,
char *nick_name);
extern void sqlGetUserInfosUseScopeIndex(
char *user_id,
int scope,
int index);
extern void sqlGetUserInfos(
char *user_id,
char *nick_name,
int *scope);
extern void sqlGetUserInfoEnd(void);
extern void sqlInsertFace(char *user_id,
char *nick_name,
char *url,
void *feature,
int size);
extern int sqlGetFaceCount(void);
extern void sqlGetFaceStart(void);
extern int sqlGetFace(char *user_id,char *nick_name,char *url,void *feature);
extern void sqlGetFaceEnd(void);
extern void sqlDeleteFace(char *id);
extern void sqlCheckBack(void);
extern void sqlInit(void);
extern void sqlInsertRecordCapNoBack(
char *date,
uint64_t picture_id);
extern void sqlInsertRecordFaceNoBack(
char *date_time,
char *face_id,
char *nick_name,
uint64_t picture_id);
extern void sqlInsertPicUrlNoBack(
uint64_t picture_id,
char *url);
extern void sqlInsertRecordUrlNoBack(
uint64_t picture_id,
char *url);
extern int sqlGetCapInfo(
uint64_t picture_id,
char *date);
extern int sqlGetPicInfoStart(uint64_t picture_id);
extern void sqlGetPicInfos(char *url);
extern void sqlGetPicInfoEnd(void);
extern int sqlGetRecordInfoStart(uint64_t picture_id);
extern void sqlGetRecordInfos(char *url);
extern void sqlGetRecordInfoEnd(void);
extern void sqlInsertRecordAlarm(
char *date_time,
int type,
int has_people,
int age,
int sex,
uint64_t picture_id);
extern int sqlGetAlarmInfoUseDateType(
char *date_time,
int type,
int *has_people);
extern void sqlInsertRecordTalkNoBack(
char *date_time,
char *people,
int call_dir,
int answered,
int talk_time,
uint64_t picture_id);
extern void sqlDeleteDeviceUseTypeNoBack(int type);
extern void sqlClearFaceNoBack(void);
extern void sqlClearDeviceNoBack(void);
extern void sqlClearRecordCaptureNoBack(void);
extern void sqlClearRecordTalkNoBack(void);
extern void sqlClearRecordFaceNoBack(void);
extern void sqlClearRecordAlarmNoBack(void);
extern void sqlClearPicUrlNoBack(void);
extern void sqlClearRecordUrlNoBack(void);
extern void sqlClearAll(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/hal/hal_mixer/CMakeLists.txt
# 查找当前目录下的所有源文件 并将名称保存到 SRCS_HAL_MIXER 变量
aux_source_directory(. SRCS_HAL_MIXER)
STRING( REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER_HAL_MIXER ${CMAKE_CURRENT_SOURCE_DIR})
# 生成链接库
add_library (${CURRENT_FOLDER_HAL_MIXER}
aplay.c
arecord.c)
<file_sep>/module/updater/verify/md5/md5sum.cpp
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <netdb.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/time.h>
#include "md5sum.h"
#define STR_VALUE(val) #val
#define STR(name) STR_VALUE(name)
#define PATH_LEN 256
int RKMD5::md5sum(char *file_name, char *md5_sum)
{
#define MD5SUM_CMD_FMT "busybox md5sum %." STR(PATH_LEN) "s 2>/dev/null"
char cmd[PATH_LEN + sizeof (MD5SUM_CMD_FMT)];
sprintf(cmd, MD5SUM_CMD_FMT, file_name);
#undef MD5SUM_CMD_FMT
int i, ch;
FILE *p = popen(cmd, "r");
if (p == NULL)
return -1;
for (i = 0; i < MD5_LEN && isxdigit(ch = fgetc(p)); i++) {
*md5_sum++ = ch;
}
*md5_sum = '\0';
pclose(p);
if (i != MD5_LEN) {
puts("Error occured!");
return -1;
} else {
return 0;
}
}
int RKMD5::readmd5sum(char *file_name, char *md5_sum)
{
int fd, ret;
fd = open(file_name, O_RDONLY);
if (fd < 0) {
printf("readmd5sum open %s failed \n", file_name);
return -1;
}
ret = read(fd, md5_sum, MD5_LEN + 1);
if (ret != MD5_LEN + 1) {
printf("readmd5sum read %s failed \n", file_name);
return -1;
}
md5_sum[MD5_LEN] = '\0';
close(fd);
return 0;
}
RKMD5::RKMD5()
{
printf("RKMD5()\n");
}
RKMD5::~RKMD5()
{
printf("~RKMD5()\n");
}
#if 0
int main(int argc, char *argv[])
{
char md5_sum[MD5_LEN + 1];
RKMD5::md5sum((char *)"./Firmware.img", md5_sum);
printf("md5_sum is: %s\n", md5_sum);
}
#endif
<file_sep>/src/gui/form_video.c
/*
* =============================================================================
*
* Filename: FormVideo.c
*
* Description: 视频通话窗口,包括录像,抓拍等
*
* Version: 1.0
* Created: 2016-02-23 15:32:24
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <time.h>
#include <string.h>
#include "externfunc.h"
#include "debug.h"
#include "screen.h"
#include "config.h"
#include "thread_helper.h"
#include "hal_battery.h"
#include "my_button.h"
#include "my_status.h"
#include "my_static.h"
#include "form_video.h"
#include "form_base.h"
#include "my_video.h"
#include "debug.h"
#include "protocol.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
extern void formSettingLoadBmp(void);
extern void screenAutoCloseStop(void);
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formVideoProc(HWND hWnd, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void formVideoTimerProc1s(HWND hwnd);
static void buttonHangupPress(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonUnlockPress(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonAnswerPress(HWND hwnd, int id, int nc, DWORD add_data);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_MAIN > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define BMP_LOCAL_PATH "video/"
#define TIME_1S (10 * 5)
#define TIME_100MS (TIME_1S / 10)
enum {
IDC_TIMER_1S = IDC_FORM_VIDEO_START,
IDC_MYSTATIC_TIME,
IDC_MYSTATIC_BATTERY,
IDC_MYSTATIC_TITLE,
IDC_MYSTATIC_TITLE_IMG,
IDC_BUTTON_UNLOCK,
IDC_BUTTON_HANGUP,
IDC_BUTTON_CAPTURE,
IDC_BUTTON_RECORD,
IDC_BUTTON_ANSWER,
IDC_STATE_COM,
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static BmpLocation base_bmps[] = {
{NULL},
};
static MyCtrlStatus ctrls_status[] = {
{0},
};
static MyCtrlStatic ctrls_static[] = {
{IDC_MYSTATIC_TITLE_IMG,MYSTATIC_TYPE_IMG_ONLY,0,0,1024,40,"",0xffffff,0x00000060},
{IDC_MYSTATIC_TIME, MYSTATIC_TYPE_TEXT_ONLY,0,0,200,40,"",0xffffff,0x00000000},
{IDC_MYSTATIC_BATTERY,MYSTATIC_TYPE_TEXT,910,0,45,34,"",0xffffff,0x00000000},
{IDC_MYSTATIC_TITLE, MYSTATIC_TYPE_TEXT_ONLY,312,0,400,40,"",0xffffff,0x00000000},
{0},
};
static MyCtrlButton ctrls_button[] = {
{IDC_BUTTON_HANGUP,MYBUTTON_TYPE_TWO_STATE,"挂断",80,451,buttonHangupPress},
{IDC_BUTTON_UNLOCK,MYBUTTON_TYPE_TWO_STATE,"开门",338,451,buttonUnlockPress},
{IDC_BUTTON_CAPTURE,MYBUTTON_TYPE_TWO_STATE,"抓拍",338,451,buttonUnlockPress},
{IDC_BUTTON_RECORD,MYBUTTON_TYPE_TWO_STATE,"录像",338,451,buttonUnlockPress},
{IDC_BUTTON_ANSWER,MYBUTTON_TYPE_TWO_STATE,"接听",338,451,buttonAnswerPress},
{0},
};
static MY_CTRLDATA ChildCtrls [] = {
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
// WS_EX_AUTOSECONDARYDC,
WS_EX_NONE,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv = {
.name = "Fvideo",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formVideoProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
};
static int form_type = FORM_VIDEO_TYPE_CAPTURE;
static FormBase* form_base = NULL;
static int auto_close_time = 0;
static int window_show_status = 0;
/* ---------------------------------------------------------------------------*/
/**
* @brief formVideoTimerProc1s 窗口相关定时函数
*
* @returns 1按键超时退出 0未超时退出
*/
/* ---------------------------------------------------------------------------*/
static void formVideoTimerProc1s(HWND hwnd)
{
static int call_time_old = 0;
int call_time = 0;
// 更新时间
if (form_type == FORM_VIDEO_TYPE_RECORD) {
call_time = my_video->videoGetRecordTime();
} else {
call_time = my_video->videoGetCallTime();
}
if (call_time != call_time_old) {
char buf[32] = {0};
sprintf(buf,"剩余时间: %d s",call_time);
SendMessage(GetDlgItem (form_base->hDlg, IDC_MYSTATIC_TIME),
MSG_MYSTATIC_SET_TITLE,(WPARAM)buf,0);
}
call_time_old = call_time;
if (auto_close_time) {
if (--auto_close_time == 0) {
ShowWindow(form_base->hDlg,SW_HIDE);
}
}
}
static void buttonHangupPress(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
if (form_type == FORM_VIDEO_TYPE_RECORD) {
my_video->recordStop();
ShowWindow(form_base->hDlg,SW_HIDE);
} else {
printf("[%s,%d]\n", __func__,__LINE__);
my_video->videoHangup(HANGUP_TYPE_BUTTON);
}
}
static void buttonUnlockPress(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
if (protocol_talk)
protocol_talk->unlock();
}
static void buttonAnswerPress(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
if (my_video)
my_video->videoAnswer(CALL_DIR_IN,DEV_TYPE_ENTRANCEMACHINE);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formVideoLoadBmp 加载主界面图片
*/
/* ---------------------------------------------------------------------------*/
static void formVideoLoadBmp(void)
{
printf("[%s]\n", __FUNCTION__);
bmpsLoad(base_bmps);
my_button->bmpsLoad(ctrls_button,BMP_LOCAL_PATH);
my_status->bmpsLoad(ctrls_status,BMP_LOCAL_PATH);
}
static void formVideoReleaseBmp(void)
{
printf("[%s]\n", __FUNCTION__);
bmpsRelease(base_bmps);
}
static void updateTitle(char *name)
{
if (name) {
SendMessage(GetDlgItem (form_base->hDlg, IDC_MYSTATIC_TITLE),
MSG_MYSTATIC_SET_TITLE,(WPARAM)name,0);
}
}
static void updateDisplay(HWND hDlg)
{
int button_status[] = {0,0,0,0,0};
int button_num = IDC_BUTTON_UNLOCK;
switch(form_type)
{
case FORM_VIDEO_TYPE_CAPTURE:
updateTitle("正在抓拍");
break;
case FORM_VIDEO_TYPE_MONITOR:
button_status[IDC_BUTTON_HANGUP - button_num] = 1;
myMoveWindow(GetDlgItem(hDlg,IDC_BUTTON_HANGUP), 467,451);
break;
case FORM_VIDEO_TYPE_RECORD:
updateTitle("正在录像");
button_status[IDC_BUTTON_HANGUP - button_num] = 1;
myMoveWindow(GetDlgItem(hDlg,IDC_BUTTON_HANGUP), 467,451);
break;
case FORM_VIDEO_TYPE_TALK_IN :
button_status[IDC_BUTTON_ANSWER - button_num] = 1;
myMoveWindow(GetDlgItem(hDlg,IDC_BUTTON_ANSWER), 467,451);
case FORM_VIDEO_TYPE_TALK_OUT :
button_status[IDC_BUTTON_UNLOCK - button_num] = 1;
button_status[IDC_BUTTON_HANGUP - button_num] = 1;
myMoveWindow(GetDlgItem(hDlg,IDC_BUTTON_UNLOCK), 258,451);
myMoveWindow(GetDlgItem(hDlg,IDC_BUTTON_HANGUP), 676,451);
break;
case FORM_VIDEO_TYPE_OUTDOOR:
if (protocol_talk->type == PROTOCOL_TALK_LAN) {
button_status[IDC_BUTTON_UNLOCK - button_num] = 1;
button_status[IDC_BUTTON_ANSWER - button_num] = 1;
button_status[IDC_BUTTON_HANGUP - button_num] = 1;
myMoveWindow(GetDlgItem(hDlg,IDC_BUTTON_UNLOCK), 208,451);
myMoveWindow(GetDlgItem(hDlg,IDC_BUTTON_ANSWER), 467,451);
myMoveWindow(GetDlgItem(hDlg,IDC_BUTTON_HANGUP), 726,451);
} else {
button_status[IDC_BUTTON_CAPTURE - button_num] = 1;
button_status[IDC_BUTTON_RECORD - button_num] = 1;
button_status[IDC_BUTTON_HANGUP - button_num] = 1;
myMoveWindow(GetDlgItem(hDlg,IDC_BUTTON_CAPTURE), 208,451);
myMoveWindow(GetDlgItem(hDlg,IDC_BUTTON_HANGUP), 467,451);
myMoveWindow(GetDlgItem(hDlg,IDC_BUTTON_RECORD), 726,451);
}
break;
default:
break;
}
int i;
for (i=0; i<sizeof(button_status)/sizeof(button_status[0]); i++) {
if (button_status[i] == 0)
ShowWindow(GetDlgItem(hDlg,button_num + i),SW_HIDE);
else
ShowWindow(GetDlgItem(hDlg,button_num + i),SW_SHOWNORMAL);
}
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_static[i].idc != 0; i++) {
ctrls_static[i].font = font20;
createMyStatic(hDlg,&ctrls_static[i]);
}
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
createMyButton(hDlg,&ctrls_button[i]);
}
for (i=0; ctrls_status[i].idc != 0; i++) {
createMyStatus(hDlg,&ctrls_status[i]);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formVideoProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ---------------------------------------------------------------------------*/
static int formVideoProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case MSG_TIMER:
{
// video界面不自动关闭
if (wParam == IDC_TIMER_1S){
formVideoTimerProc1s(hDlg);
return 0;
}
} break;
case MSG_SHOWWINDOW:
{
if (wParam == SW_SHOWNORMAL) {
updateDisplay(hDlg);
if (window_show_status == 1)
return 0;
window_show_status = 1;
SendMessage(Screen.getCurrent(),MSG_DISABLE_WINDOW,0,0);
} else if (wParam == SW_HIDE) {
if (window_show_status == 0)
return 0;
window_show_status = 0;
SendMessage(Screen.getCurrent(),MSG_ENABLE_WINDOW,0,0);
}
} break;
case MSG_LBUTTONDOWN:
{
// if (Public.LCDLight == 0) {
// screensaverSet(LCD_ON);
// return;
// }
} break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormVideo(HWND hMainWnd,int type,void (*callback)(void),int count)
{
HWND Form = Screen.Find(form_base_priv.name);
form_type = type;
auto_close_time = count;
if(Form) {
screenAutoCloseStop();
SendMessage(GetDlgItem (form_base->hDlg, IDC_MYSTATIC_TIME),
MSG_MYSTATIC_SET_TITLE,(WPARAM)"",0);
updateTitle("");
ShowWindow(Form,SW_SHOWNORMAL);
} else {
formVideoLoadBmp();
form_base_priv.callBack = callback;
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
static void interfaceCreateFormVideoDirect(int type,char *name,int dir)
{
switch (type)
{
case DEV_TYPE_UNDEFINED:
case DEV_TYPE_HOUSEHOLDAPP:
case DEV_TYPE_SECURITYSTAFFAPP:
case DEV_TYPE_INNERDOORMACHINE:
createFormVideo(0,FORM_VIDEO_TYPE_MONITOR,NULL,0);
break;
case DEV_TYPE_ENTRANCEMACHINE:
case DEV_TYPE_HOUSEENTRANCEMACHINE:
screensaverSet(1);
if (protocol_talk->type == PROTOCOL_TALK_LAN)
createFormVideo(0,FORM_VIDEO_TYPE_OUTDOOR,NULL,0);
else {
if (dir == CALL_DIR_OUT)
createFormVideo(0,FORM_VIDEO_TYPE_TALK_OUT,NULL,0);
else
createFormVideo(0,FORM_VIDEO_TYPE_TALK_IN,NULL,0);
}
break;
default:
break;
}
updateTitle(name);
}
static void interfaceHangup(void)
{
ShowWindow(form_base->hDlg,SW_HIDE);
}
static void interfaceAnswer(char *name)
{
updateTitle(name);
ShowWindow(GetDlgItem(form_base->hDlg,IDC_BUTTON_ANSWER),SW_HIDE);
}
void formVideoInitInterface(void)
{
if (protocol_talk) {
protocol_talk->uiShowFormVideo = interfaceCreateFormVideoDirect;
protocol_talk->uiHangup = interfaceHangup;
protocol_talk->uiAnswer = interfaceAnswer;
}
}
<file_sep>/src/app/debug.h
/*
* =============================================================================
*
* Filename: debug.h
*
* Description: 调试接口
*
* Version: 1.0
* Created: 2016-11-26 22:38:57
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _TC_DEBUG_H
#define _TC_DEBUG_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <stdint.h>
#define NELEMENTS(array) /* number of elements in an array */ \
(sizeof (array) / sizeof ((array) [0]))
#define DPRINT(...) \
do { \
printf("\033[1;34;40m"); \
printf(__VA_ARGS__); \
printf("\033[0m"); \
} while (0)
#define DBG_FLAG(x) DPRINT("flag------->[%ld]\n",x)
#define DBG_STR(x) DPRINT("flag------->[%s]\n",x)
void debugInit(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/udp_talk/udp_talk_protocol.h
/*
* =============================================================================
*
* Filename: protocol_video.h
*
* Description: 太川对讲协议
*
* Version: 1.0
* Created: 2018-12-13 14:21:32
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _VIDEO_PROTOCOL_H
#define _VIDEO_PROTOCOL_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <stdint.h>
#define COMM_TIME 10 // 呼叫超时时间S
#define SHAKE_TIME 13 // 握手超时时间S
#define TALK_TIME 180 // 对讲时间
#define RING_TIME 31 // 响铃时间
#define LEAVE_WORD_TIME 11 // 留言时间
#define CALL_OK 0
#define CALL_NOHOST -1
#define CALL_FAIL -2
#define CALL_BUSY -3
#define CALL_WAIT -4
#define MAXFJCOUNT 6
#define FJ_REGIST_TIME (65000) // 分机注册时间间隔 64秒,兼容芯唐版本时间
typedef enum _VideoProtoclType {
VIDEOTRANS_PROTOCOL_3000, // 3000协议
VIDEOTRANS_PROTOCOL_U9, // U9协议
}VideoProtoclType;
typedef enum _VideoCallDir{
VIDEOTRANS_CALL_DIR_IN, // 呼入
VIDEOTRANS_CALL_DIR_OUT, // 呼出
}VideoCallDir;
typedef enum _VideoUiStatus{
VIDEOTRANS_UI_NONE, // 不做处理
VIDEOTRANS_UI_SHAKEHANDS, // 3000握手命令
VIDEOTRANS_UI_CALLIP, // 呼出
VIDEOTRANS_UI_RING, // 呼入响铃
VIDEOTRANS_UI_LEAVE_WORD, // 留言
VIDEOTRANS_UI_RETCALL, // 呼出到管理中心,室内机收到回应
VIDEOTRANS_UI_RETCALL_MONITOR, // 呼出到门口机,户门口机收到回应,显示开锁按钮
VIDEOTRANS_UI_FAILCOMM, // 通信异常
VIDEOTRANS_UI_FAILSHAKEHANDS, // 握手异常
VIDEOTRANS_UI_FAILBUSY, // 对方忙
VIDEOTRANS_UI_FAILABORT, // 突然中断
VIDEOTRANS_UI_ANSWER, // 本机接听
VIDEOTRANS_UI_ANSWER_EX, // 分机接听
VIDEOTRANS_UI_OVER, // 挂机
}VideoUiStatus;
typedef enum _VideoProtocolStatus {
VIDEOTRANS_STATUS_NULL, // 不在通话或响铃状态
VIDEOTRANS_STATUS_RING, // 响铃状态,倒计时30秒
VIDEOTRANS_STATUS_TALK, // 通话状态,倒计时180秒
}VideoProtocolStatus;
struct _VideoPriv;
struct _VideoInterface;
typedef struct _VideoTrans {
struct _VideoPriv *priv;
struct _VideoInterface *interface;
/* ---------------------------------------------------------------------------*/
/**
* @brief 使能通话对讲,(无机身码时不能对讲)
*
* @param
*/
/* ---------------------------------------------------------------------------*/
void (*enable)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 呼叫
*
* @param
* @param ip 呼叫对方IP
*/
/* ---------------------------------------------------------------------------*/
void (*call)(struct _VideoTrans *,char *ip);
/* ---------------------------------------------------------------------------*/
/**
* @brief 接听
*
* @param
*/
/* ---------------------------------------------------------------------------*/
void (*answer)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 留言
*
* @param
*/
/* ---------------------------------------------------------------------------*/
void (*leaveWord)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 挂机
*
* @param
*/
/* ---------------------------------------------------------------------------*/
void (*hangup)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 呼叫超时调用此接口
*
* @param
*/
/* ---------------------------------------------------------------------------*/
void (*callBackOverTime)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 通话中开锁
*
* @param
*/
/* ---------------------------------------------------------------------------*/
void (*unlock)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 获取通话方IP
*
* @param
*
* @returns 返回对方IP
*/
/* ---------------------------------------------------------------------------*/
char *(*getPeerIP)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 获取通话端口
*
* @param
*
* @returns 返回端口
*
*/
/* ---------------------------------------------------------------------------*/
int (*getTalkPort)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 获得通话对方名称
*
* @param
*
* @returns 返回名称
*/
/* ---------------------------------------------------------------------------*/
char *(*dispCallName)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 判断是否在空闲状态
*
* @param
*
* @returns 1空闲 0非空闲
*/
/* ---------------------------------------------------------------------------*/
int (*getIdleStatus)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 判断是否在通话状态
*
* @param
*
* @returns 1通话 0非通话
*/
/* ---------------------------------------------------------------------------*/
int (*getTalkStatus)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 获取是否有未读留言
*
* @param
*
* return 1有未读留言 0无未读留言
*/
/* ---------------------------------------------------------------------------*/
int (*hasUnreadLeaveWord)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 清除未读留言
*
* @param
*/
/* ---------------------------------------------------------------------------*/
void (*clearUnreadLeaveWord)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 分机注册函数,接收其他分机向本机注册
*
* @param
* @param ip 分机IP
* @param port 分机端口
* @param type 分机协议类型 TP_PHONE_REGISTER
* @param data 分机数据
*/
/* ---------------------------------------------------------------------------*/
void (*registDev)(struct _VideoTrans *,char *ip,int port,int type,char *data);
/* ---------------------------------------------------------------------------*/
/**
* @brief 获取已注册分机结构体的首地址,itesdk里重新定义结构体使用
*
* @param
*
* @returns 分机结构体数组首地址
*/
/* ---------------------------------------------------------------------------*/
void *(*getRegistDev)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 获取指定下标分机的IP
*
* @param
* @param index 指定下标
*
* @returns IP
*/
/* ---------------------------------------------------------------------------*/
char *(*getRegistOneDevIp)(struct _VideoTrans *,int index);
/* ---------------------------------------------------------------------------*/
/**
* @brief 作为分机时,向主机注册地址,
*
* @param
* @param type 注册分机的类型 TP_U9_REGISTER
*/
/* ---------------------------------------------------------------------------*/
void (*registToMaster)(struct _VideoTrans *,int type);
/* ---------------------------------------------------------------------------*/
/**
* @brief 获得当前通话倒计时显示
*
* @param
* @param disp_string 显示字符
* @returns 1成功 0失败
*/
/* ---------------------------------------------------------------------------*/
VideoProtocolStatus (*dispCallTime)(struct _VideoTrans *,int *disp_time);
/* ---------------------------------------------------------------------------*/
/**
* @brief 切换协议时重新创建状态机线程
*
* @param type 协议类型
*/
/* ---------------------------------------------------------------------------*/
void (*resetProtocol)(struct _VideoTrans *,VideoProtoclType type);
/* ---------------------------------------------------------------------------*/
/**
* @brief 接收通话对接协议
*
* @param
* @param ip 对方IP
* @param port 对方端口
* @param data 协议数据
* @param size 数据大小
*/
/* ---------------------------------------------------------------------------*/
void (*cmdHandle)(struct _VideoTrans *,
char *ip,int port, char *data,int size);
/* ---------------------------------------------------------------------------*/
/**
* @brief 设置当前对讲状态为忙状态,用于云对讲时,不能进入此状态机
*
*/
/* ---------------------------------------------------------------------------*/
void (*setStatusBusy)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 设置当前对讲状态为空闲状态,用于退出云对讲时,可以进入此状态机
*
*/
/* ---------------------------------------------------------------------------*/
void (*setStatusIdle)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 销毁通话功能
*
* @param
*/
/* ---------------------------------------------------------------------------*/
void (*destroy)(struct _VideoTrans *);
}VideoTrans;
// 需要实现的接口
typedef struct _VideoInterface {
/* ---------------------------------------------------------------------------*/
/**
* @brief uint64_t 获取系统时间tick
*
* @param
*/
/* ---------------------------------------------------------------------------*/
uint64_t (*getSystemTick)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief uint64_t 计算当前tick与上一次记录的差值
*
* @param
* @param cur 当前tick
* @param old 上一次tick
*
* return 差值
*/
/* ---------------------------------------------------------------------------*/
uint64_t (*getDiffSysTick)(struct _VideoTrans *,uint64_t cur,uint64_t old);
/* ---------------------------------------------------------------------------*/
/**
* @brief 使用UDP底层发送协议
*
* @param
* @param ip 目的IP
* @param port 目的端口
* @param data 数据
* @param size 数据大小
* @param enable_call_back 是否使用回调函数
*/
/* ---------------------------------------------------------------------------*/
void (*udpSend)(struct _VideoTrans *,
char *ip,int port,void *data,int size,int enable_call_back);
/* ---------------------------------------------------------------------------*/
/**
* @brief 保存通话记录
*
* @param
* @param dir VideoCallDir 呼入或者呼出
* @param name
* @param ip
*/
/* ---------------------------------------------------------------------------*/
void (*saveRecordAsync)(struct _VideoTrans *,VideoCallDir dir,char *name,char *ip);
/* ---------------------------------------------------------------------------*/
/**
* @brief 发送状态消息,用于UI提示当前状态及回调处理
*
* @param
* @param status VideoUiStatus
*/
/* ---------------------------------------------------------------------------*/
void (*sendMessageStatus)(struct _VideoTrans *,VideoUiStatus status);
/* ---------------------------------------------------------------------------*/
/**
* @brief 显示呼叫窗口
*
* @param
*/
/* ---------------------------------------------------------------------------*/
void (*showCallWindow)(struct _VideoTrans *);
/* ---------------------------------------------------------------------------*/
/**
* @brief int 判断是否为管理中心Center,门口机Dmk,户门口机HDmk
*
* @param
* @param ip 输入IP
* @return -1非判断目标,>=0目标下标,比如0,第0个管理中心等
*/
/* ---------------------------------------------------------------------------*/
int (*isCenter)(struct _VideoTrans *,char *ip);
int (*isDmk)(struct _VideoTrans *,char *ip);
int (*isHDmk)(struct _VideoTrans *,char *ip);
/* ---------------------------------------------------------------------------*/
/**
* @brief 取得门口机Dmk,户门口机HDmk名称
*
* @param
* @param index 目标下标
*
* @returns 返回名称字符串
*/
/* ---------------------------------------------------------------------------*/
char *(*getDmkName)(struct _VideoTrans *,int index);
char *(*getHDmkName)(struct _VideoTrans *,int index);
}VideoInterface;
/* ---------------------------------------------------------------------------*/
/**
* @brief videoTransCreate 创建对讲对象
*
* @param interface 需实现的接口函数
* @param port 端口
* @param call_cmd 呼叫命令 TP_CALL
* @param device_type 设备类型 TYPE_USER
* @param type 3000协议orU9协议
* @param master_ip 主机IP
* @param room_name 本机住户地址名称
* @param room_id 本机住户ID
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
extern VideoTrans * videoTransCreate(VideoInterface *interface,
int port,
int call_cmd,
int device_type,
VideoProtoclType type,
char *master_ip,
char *room_name,
char *room_id);
extern VideoTrans *protocol_video;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/config.h
#ifndef CONFIG_H
#define CONFIG_H
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <time.h>
#include "iniparser/iniparser.h"
#ifdef __cplusplus
extern "C" {
#endif
#define DEVICE_TYPE "TC-U9MY-A"
#define DEVICE_SVERSION "1.0.8"
#if (defined X86)
#define SDCARD_PATH "./"
#define AUDIO_PATH "./res/wav/"
#define CONFIG_FILE_PATH "./"
#define UPDATE_INI_PATH "./"
#else
#define SDCARD_PATH "/mnt/sdcard/"
#define AUDIO_PATH "/root/usr/res/wav/"
#define CONFIG_FILE_PATH "/data/"
#define UPDATE_INI_PATH "/tmp/"
#endif
#define DATABSE_PATH "./" // 数据库文件路径
#define QRCODE_IMIE "./imei.png" // 机身码二维码路径
#define QRCODE_APP "./app_url.png" // app地址二维码路径
#define CONFIG_FILENAME CONFIG_FILE_PATH"config.ini" // 配置文件,包括机身号等只配置一次的文件
#define CONFIG_PARA_FILENAME CONFIG_FILE_PATH"config_para.ini" // 配置文件,参数设置,可以删除后恢复
#define CAP_PATH SDCARD_PATH"cap/" // SD卡抓拍存储目录
#define TALK_PATH SDCARD_PATH"talk/" // SD卡通话抓拍记录
#define ALARM_PATH SDCARD_PATH"alarm/" // SD卡报警抓拍记录
#define FACE_PATH SDCARD_PATH"face/" // SD卡人脸抓拍记录
#define FAST_PIC_PATH "/tmp/cap/" // 快速启动抓拍路径,放到内存中
#define IPC_MAIN "/tmp/ipc_main" // 主进程
#define IPC_UART "/tmp/ipc_uart" // 串口处理进程
#define IPC_CAMMER "/tmp/ipc_cammer" // 摄像头处理进程
#define QINIU_URL "http://img.cateye.taichuan.com" // 七牛云存储地址
#define UPDATE_FILE "/tmp/Update.cab" // LAN升级时,升级包存放位置
#define UPDATE_URL "http://img.cateye.taichuan.com/update.ini" // 七牛云存储升级包配置文件地址
#define UPDATE_INI UPDATE_INI_PATH"update.ini" // 七牛云存储升级配置文件地址
#define UPDATE_IMG "update_img.tar.gz" // SD卡升级包存储位置
#define UPDATE_APP "update.tar.gz" // SD卡升级包存储位置
#define SLEEP_LONG_TIMER 50
#define POWEROFF_TIMER 2
#define MAX_RINGS_NUM 5
typedef struct _EtcValueChar {
const char* section;
const char* key;
char *value;
unsigned int leng;
const char *default_char;
} EtcValueChar;
typedef struct _EtcValueInt {
const char* section;
const char* key;
int *value;
int default_int;
} EtcValueInt;
struct DevConfig{
char device_name[64];
char product_key[64];
char device_secret[64];
};
typedef struct {
// ethernet
int enable;
// station
char ssid[64 + 1];
char mode[64 + 1];
char security[128 + 1];
char password[64 + 1];
char running[64 + 1];
}TcWifiConfig;
enum {
TC_SET_STATION,
TC_SET_AP,
};
typedef void (*configCallback)(void);
/* encry type */
enum AWSS_ENC_TYPE {
AWSS_ENC_TYPE_NONE,
AWSS_ENC_TYPE_WEP,
AWSS_ENC_TYPE_TKIP,
AWSS_ENC_TYPE_AES,
AWSS_ENC_TYPE_TKIPAES,
AWSS_ENC_TYPE_MAX = AWSS_ENC_TYPE_TKIPAES,
AWSS_ENC_TYPE_INVALID = 0xff,
};
/* auth type */
enum AWSS_AUTH_TYPE {
AWSS_AUTH_TYPE_OPEN,
AWSS_AUTH_TYPE_SHARED,
AWSS_AUTH_TYPE_WPAPSK,
AWSS_AUTH_TYPE_WPA8021X,
AWSS_AUTH_TYPE_WPA2PSK,
AWSS_AUTH_TYPE_WPA28021X,
AWSS_AUTH_TYPE_WPAPSKWPA2PSK,
AWSS_AUTH_TYPE_MAX = AWSS_AUTH_TYPE_WPAPSKWPA2PSK,
AWSS_AUTH_TYPE_INVALID = 0xff,
};
enum TC_AUTH_TYPE {
TC_AUTH_TYPE_OPEN = 0,
TC_AUTH_TYPE_SHARED = (1 << 0),
TC_AUTH_TYPE_WPAPSK = (1 << 1),
TC_AUTH_TYPE_WPA8021X = (1 << 2),
TC_AUTH_TYPE_WPA2PSK = (1 << 3),
TC_AUTH_TYPE_WPA28021X = (1 << 4),
TC_AUTH_TYPE_WPAPSKWPA2PSK = (1 << 5),
TC_AUTH_TYPE_MAX = TC_AUTH_TYPE_WPAPSKWPA2PSK,
TC_AUTH_TYPE_INVALID = 0xff,
};
typedef struct _TcWifiScan{
char ssid[64 + 1]; // 账号
uint8_t bssid[16 + 1]; // mac地址
enum AWSS_AUTH_TYPE auth;
enum AWSS_ENC_TYPE encry;
uint8_t channel;
signed char rssi;
}TcWifiScan;
struct wifiLowPower {
char local_ip[16 + 1]; // 本机地址
char dst_ip[16 + 1]; // 目的地址
char dst_port[8 + 1]; // 目的端口
char dst_mac[20 + 1]; // 目的mac地址
};
struct CapType {
int type; // 0 图片 1 录像
int count; // 抓拍图片数量
int timer; // 录像时间长短
};
struct Mute {
int state; // 0关闭免扰 1打开免扰
int start_time; // 免扰开始时间
int end_time; // 免扰结束时间
};
typedef struct _Config {
char imei[64 + 1]; // 设备机身码
char hardcode[64 + 1]; // 设备硬件码
char version[16 + 1]; // 软件版本
char k_version[16 + 1]; // 内核版本,不写入配置文件中
char s_version[2 + 1]; // 单片机版本,不写入配置文件中
char app_url[128 + 1]; // app地址,暂时不用
int timestamp; // 启动时间戳
TcWifiConfig net_config; // 网络设置
char f_license[128 + 1]; // 阅面人脸
int ring_num; // 铃声编号
int ring_volume; // 门铃音量
int alarm_volume; // 报警音量
int talk_volume; // 对讲音量
int pir_active_timer; // PIR触发多少秒后报警
int pir_alarm; // PIR触发是否发出报警音
int pir_strength; // PIR触发强度,0近,1中,2远
int screensaver_time; // 息屏时间
int brightness; // 屏幕亮度
int record_time; // 主界面录像倒计时时间
struct Mute mute; // 免扰模式参数
int auto_sync_time; // 是否自动同步时间
int face_enable; // 是否开启人脸识别功能0关闭,1开启
int sleep_time; // 休眠时间
struct wifiLowPower wifi_lowpower; // 低功耗wifi参数
struct CapType cap_doorbell;// 按门铃抓拍或录像
struct CapType cap_alarm; // 报警时抓拍或录像
struct CapType cap_talk; // 通话时抓拍或录像
} Config;
void configLoad(void);
void ConfigSavePrivate(void);
void ConfigSavePrivateCallback(configCallback func);
void ConfigSavePublic(void);
void ConfigSavePublicCallback(configCallback func);
void createSdcardDirs(void);
void configLoadEtcChar(dictionary *cfg_ini, EtcValueChar *etc_file,
unsigned int length);
extern Config g_config;
#ifdef __cplusplus
}
#endif
#endif /* CONFIG_H */
<file_sep>/src/gui/form_setting_mute.c
/*
* =============================================================================
*
* Filename: form_setting_Mute.c
*
* Description: 免扰设置界面
*
* Version: 1.0
* Created: 2018-03-01 23:32:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <string.h>
#include "screen.h"
#include "iwlib.h"
#include "my_button.h"
#include "my_title.h"
#include "config.h"
#include "externfunc.h"
#include "thread_helper.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
extern int createFormSettingTimeStart(HWND hMainWnd,void (*callback)(void),int time_buf,void (*saveCallback)(int ));
extern int createFormSettingTimeEnd(HWND hMainWnd,void (*callback)(void),int time_buf,void (*saveCallback)(int ));
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formSettingMuteProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void MuteLoadData(void *ap_info,int ap_cnt);
static void buttonTitleNotify(HWND hwnd, int id, int nc, DWORD add_data);
static void reloadTimer(HWND hwnd);
static void saveStartTime(int time_buf);
static void saveEndTime(int time_buf);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_SET_LOCAL > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define BMP_LOCAL_PATH "setting/"
enum {
IDC_TIMER_1S = IDC_FORM_SETTING_MUTE,
IDC_STATIC_IMG_WARNING,
IDC_STATIC_TEXT_WARNING,
IDC_SCROLLVIEW,
IDC_TITLE,
};
enum {
SCROLLVIEW_ITEM_TYPE_TITLE,
SCROLLVIEW_ITEM_TYPE_LIST,
};
struct ScrollviewItem {
char title[32]; // 左边标题
char text[32]; // 右边文字
int (*callback)(HWND,void (*)(void),int,void (*)(int) ); // 点击回调函数
void (*saveCallback)(int ); // 设置返回保存回调函数
int index; // 元素位置
int time_buf; // 当前设定时间
};
// 控件滑动相关操作
#define FILL_BMP_STRUCT(left,top,img) \
FillBoxWithBitmap(hdc,left, top,img.bmWidth,img.bmHeight,&img)
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static HWND hScrollView;
static int bmp_load_finished = 0;
static int flag_timer_stop = 0;
static BITMAP bmp_warning; // 警告
static BITMAP bmp_security; // 加密
static BITMAP bmp_select; // 选中
static BITMAP bmp_enter; // 进入
static struct ScrollviewItem locoal_list[] = {
{"开始时间","",createFormSettingTimeStart,saveStartTime},
{"结束时间","",createFormSettingTimeEnd,saveEndTime},
{0},
};
static BmpLocation bmp_load[] = {
{&bmp_warning, BMP_LOCAL_PATH"ico_警告.png"},
{&bmp_security, BMP_LOCAL_PATH"ico_lock.png"},
{&bmp_select, BMP_LOCAL_PATH"ico_对.png"},
{&bmp_enter, BMP_LOCAL_PATH"ico_返回_1.png"},
{NULL},
};
static MY_CTRLDATA ChildCtrls [] = {
STATIC_IMAGE(452,216,120,120,IDC_STATIC_IMG_WARNING,(DWORD)&bmp_warning),
STATIC_LB(0,358,1024,25,IDC_STATIC_TEXT_WARNING,"免扰已关闭,请点击开关开启",&font20,0xffffff),
SCROLLVIEW(0,40,1024,390,IDC_SCROLLVIEW),
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
WS_EX_NONE ,//| WS_EX_AUTOSECONDARYDC,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "FsetMute",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formSettingMuteProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
.auto_close_time_set = 10,
};
static MyCtrlTitle ctrls_title[] = {
{
IDC_TITLE,
MYTITLE_LEFT_EXIT,
MYTITLE_RIGHT_SWICH,
0,0,1024,40,
"免扰设置",
"",
0xffffff, 0x333333FF,
buttonTitleNotify,
},
{0},
};
static MyCtrlButton ctrls_button[] = {
{0},
};
static FormBase* form_base = NULL;
static void enableAutoClose(void)
{
reloadTimer(form_base->hDlg);
Screen.setCurrent(form_base_priv.name);
flag_timer_stop = 0;
}
static void saveStartTime(int time_buf)
{
g_config.mute.start_time = time_buf;
ConfigSavePublic();
}
static void saveEndTime(int time_buf)
{
g_config.mute.end_time = time_buf;
ConfigSavePublic();
}
/* ---------------------------------------------------------------------------*/
/**
* @brief reloadTimer 切换是否连接Mute
*
* @param hwnd
* @param on_off
*/
/* ---------------------------------------------------------------------------*/
static void reloadTimer(HWND hwnd)
{
if (g_config.mute.state) {
int i;
SVITEMINFO svii;
struct ScrollviewItem *plist = locoal_list;
SendMessage (hScrollView, SVM_RESETCONTENT, 0, 0);
for (i=0; plist->title[0] != 0; i++) {
plist->index = i;
svii.nItemHeight = 60;
svii.addData = (DWORD)plist;
svii.nItem = i;
if (strcmp("开始时间",plist->title) == 0) {
plist->time_buf = g_config.mute.start_time;
sprintf(plist->text,"%d:%02d",plist->time_buf / 60,plist->time_buf % 60);
} else if (strcmp("结束时间",plist->title) == 0) {
plist->time_buf = g_config.mute.end_time;
sprintf(plist->text,"%d:%02d",plist->time_buf / 60,plist->time_buf % 60);
}
SendMessage (hScrollView, SVM_ADDITEM, 0, (LPARAM)&svii);
SendMessage (hScrollView, SVM_SETITEMADDDATA, i, (DWORD)plist);
plist++;
}
ShowWindow(GetDlgItem(hwnd,IDC_STATIC_IMG_WARNING),SW_HIDE);
ShowWindow(GetDlgItem(hwnd,IDC_STATIC_TEXT_WARNING),SW_HIDE);
ShowWindow(GetDlgItem(hwnd,IDC_SCROLLVIEW),SW_SHOWNORMAL);
} else {
ShowWindow(GetDlgItem(hwnd,IDC_STATIC_IMG_WARNING),SW_SHOWNORMAL);
ShowWindow(GetDlgItem(hwnd,IDC_STATIC_TEXT_WARNING),SW_SHOWNORMAL);
ShowWindow(GetDlgItem(hwnd,IDC_SCROLLVIEW),SW_HIDE);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief saveConfigCallback 切换Mute开关,保存配置后回调函数
*/
/* ---------------------------------------------------------------------------*/
static void saveConfigCallback(void)
{
reloadTimer(form_base->hDlg);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief buttonTitleNotify 标题按钮
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ---------------------------------------------------------------------------*/
static void buttonTitleNotify(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc == MYTITLE_BUTTON_EXIT) {
ShowWindow(GetParent(hwnd),SW_HIDE);
}
else if (nc == MYTITLE_BUTTON_SWICH) {
g_config.mute.state = add_data;
ConfigSavePublicCallback(saveConfigCallback);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief scrollviewNotify
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ---------------------------------------------------------------------------*/
static void scrollviewNotify(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != SVN_CLICKED)
return;
int idx = SendMessage (hScrollView, SVM_GETCURSEL, 0, 0);
struct ScrollviewItem *plist;
plist = (struct ScrollviewItem *)SendMessage (hScrollView, SVM_GETITEMADDDATA, idx, 0);
if (!plist)
return;
if (!plist->callback)
return;
flag_timer_stop = 1;
plist->callback(hwnd,enableAutoClose,plist->time_buf,plist->saveCallback);
}
void formSettingMuteLoadBmp(void)
{
if (bmp_load_finished == 1)
return;
printf("[%s]\n", __FUNCTION__);
bmpsLoad(bmp_load);
bmp_load_finished = 1;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myDrawItem 列表自定义绘图函数
*
* @param hWnd
* @param hsvi
* @param hdc
* @param rcDraw
*/
/* ---------------------------------------------------------------------------*/
static void myDrawItem (HWND hWnd, HSVITEM hsvi, HDC hdc, RECT *rcDraw)
{
#define FILL_BMP_STRUCT(left,top,img) \
FillBoxWithBitmap(hdc,left, top,img.bmWidth,img.bmHeight,&img)
#define DRAW_TABLE(rc,offset,color) \
do { \
SetPenColor (hdc, color); \
if (p_item->index) { \
MoveTo (hdc, rc->left + offset, rc->top); \
LineTo (hdc, rc->right,rc->top); \
} \
MoveTo (hdc, rc->left + offset, rc->bottom); \
LineTo (hdc, rc->right,rc->bottom); \
} while (0)
struct ScrollviewItem *p_item = (struct ScrollviewItem *)scrollview_get_item_adddata (hsvi);
SetBkMode (hdc, BM_TRANSPARENT);
SetTextColor (hdc, PIXEL_lightwhite);
SelectFont (hdc, font20);
if (p_item->callback)
FILL_BMP_STRUCT(rcDraw->left + 968,rcDraw->top + 15,bmp_enter);
// 绘制表格
DRAW_TABLE(rcDraw,0,0xCCCCCC);
// 输出文字
TextOut (hdc, rcDraw->left + 30, rcDraw->top + 15, p_item->title);
RECT rc;
memcpy(&rc,rcDraw,sizeof(RECT));
rc.left += 512;
rc.right -= 70;
SetTextColor (hdc, 0xCCCCCC);
DrawText (hdc,p_item->text, -1, &rc,
DT_VCENTER | DT_RIGHT | DT_WORDBREAK | DT_SINGLELINE);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief MuteLoadData 重新加载Mute列表
*
* @param aps
* @param ap_cnt
*/
/* ---------------------------------------------------------------------------*/
static void MuteLoadData(void *aps,int ap_cnt)
{
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_title[i].idc != 0; i++) {
ctrls_title[i].font = font20;
createMyTitle(hDlg,&ctrls_title[i]);
}
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
createMyButton(hDlg,&ctrls_button[i]);
}
hScrollView = GetDlgItem (hDlg, IDC_SCROLLVIEW);
SendMessage (hScrollView, SVM_SETITEMDRAW, 0, (LPARAM)myDrawItem);
SendMessage(GetDlgItem(hDlg,IDC_TITLE),
MSG_MYTITLE_SET_SWICH, (WPARAM)g_config.mute.state, 0);
reloadTimer(form_base->hDlg);
}
/* ----------------------------------------------------------------*/
/**
* @brief formSettingMuteProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ----------------------------------------------------------------*/
static int formSettingMuteProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
switch(message) // 自定义消息
{
case MSG_TIMER:
{
if (flag_timer_stop)
return 0;
} break;
case MSG_COMMAND:
{
int id = LOWORD (wParam);
int code = HIWORD (wParam);
scrollviewNotify(hDlg,id,code,0);
break;
}
case MSG_ENABLE_WINDOW:
enableAutoClose();
break;
case MSG_DISABLE_WINDOW:
flag_timer_stop = 1;
break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormSettingMute(HWND hMainWnd,void (*callback)(void))
{
HWND Form = Screen.Find(form_base_priv.name);
if(Form) {
Screen.setCurrent(form_base_priv.name);
reloadTimer(form_base->hDlg);
ShowWindow(Form,SW_SHOWNORMAL);
} else {
if (bmp_load_finished == 0) {
return 0;
}
form_base_priv.callBack = callback;
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
<file_sep>/src/app/udp_talk/udp_client.h
#ifndef TUDPClientH
#define TUDPClientH
#ifdef __cplusplus
extern "C" {
#endif
//---------------------------------------------------------------------------
// 设置可靠发送的重发次数(含首次发送)为3次
#ifndef FALSE
#define FALSE 0
#define TRUE 1
#define BOOL int
#endif
typedef struct _TUDPClient
{
#ifndef WIN32
int m_socket;
#else
unsigned m_socket;
#endif
void (* Destroy)(struct _TUDPClient *This);
void (* Clear)(struct _TUDPClient *This);
int (* RecvBuffer)(struct _TUDPClient *This,void *buf,int count,int TimeOut,
void * from,int * fromlen);
int (* SendBuffer)(struct _TUDPClient *This,const char *IP,int port,const void *buf,int count);
int (* TrusthSend)(struct _TUDPClient *This,const char *IP,int port,const void *buf,int count);
int (* TrusthRecv)(struct _TUDPClient *This,void *buf,int count,int TimeOut);
} TUDPClient;
extern TUDPClient *udpclient;
//---------------------------------------------------------------------------
// 创建一个UDP客户端,Port为0则不绑定端口
TUDPClient* TUDPClient_Create(int Port);
#ifdef __cplusplus
}
#endif
#endif
<file_sep>/module/video/process/md_encoder_process.cpp
/*
* =============================================================================
*
* Filename: encoder_process.c
*
* Description: H264编码
*
* Version: 1.0
* Created: 2019-06-19 22:57:16
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <adk/mm/cma_allocator.h>
#include <adk/utils/assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "h264_enc_dec/md_mpi_enc_api.h"
#include "md_encoder_process.h"
#include "thread_helper.h"
#include "libyuv.h"
#include "debug.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
using namespace rk;
#define ALIGN(value, bits) (((value) + ((bits) - 1)) & (~((bits) - 1)))
#define ALIGN_CUT(value, bits) ((value) & (~((bits) - 1)))
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
#define IAMGE_MAX_W 1280
#define IAMGE_MAX_H 720
#define IMAGE_MAX_DATA (IAMGE_MAX_W * IAMGE_MAX_H * 3 / 2 )
typedef struct _H264Data {
int get_data_end;
int type;
int w,h;
unsigned char data[IMAGE_MAX_DATA];
}H264Data;
#define ENCODE_LOG(...) \
do { \
printf("\033[1;34;40m"); \
printf("[h264encoder]"); \
printf(__VA_ARGS__); \
printf("\033[0m"); \
} while (0)
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static H264Data h264_info;
static pthread_mutex_t enc_mutex;
int NV12Scale(unsigned char *psrc_buf, int psrc_w, int psrc_h, unsigned char **pdst_buf, int pdst_w, int pdst_h)
{
libyuv::FilterModeEnum pfmode = libyuv::kFilterNone;
unsigned char *i420_buf1 = (unsigned char *)malloc((psrc_w * psrc_h * 3) >> 1);
unsigned char *i420_buf2 = (unsigned char *)malloc((pdst_w * pdst_h * 3) >> 1);
*pdst_buf = (unsigned char *)malloc((pdst_w * pdst_h * 3) >> 1);
/* NV12_1920x1080 -> I420_1920x1080 */
libyuv::NV12ToI420(&psrc_buf[0], psrc_w,
&psrc_buf[psrc_w * psrc_h], psrc_w,
&i420_buf1[0], psrc_w,
&i420_buf1[psrc_w * psrc_h], psrc_w >> 1,
&i420_buf1[(psrc_w * psrc_h * 5) >> 2], psrc_w >> 1,
psrc_w, psrc_h);
/* I420_1920x1080 -> I420_1280x720 */
libyuv::I420Scale(&i420_buf1[0], psrc_w,
&i420_buf1[psrc_w * psrc_h], psrc_w >> 1,
&i420_buf1[(psrc_w * psrc_h * 5) >> 2], psrc_w >> 1,
psrc_w, psrc_h,
&i420_buf2[0], pdst_w,
&i420_buf2[pdst_w * pdst_h], pdst_w >> 1,
&i420_buf2[(pdst_w * pdst_h * 5) >> 2], pdst_w >> 1,
pdst_w, pdst_h,
pfmode);
/* I420_1280x720 -> NV12_1280x720 */
libyuv::I420ToNV12(&i420_buf2[0], pdst_w,
&i420_buf2[pdst_w * pdst_h], pdst_w >> 1,
&i420_buf2[(pdst_w * pdst_h * 5) >> 2], pdst_w >> 1,
*pdst_buf, pdst_w,
&(*pdst_buf)[pdst_w * pdst_h], pdst_w,
pdst_w,pdst_h);
free(i420_buf1);
free(i420_buf2);
return 0;
}
static void* encoderProcessThread(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
H264Encoder *process = (H264Encoder *)arg;
while (process->start_enc() == true) {
if (h264_info.get_data_end == 0) {
usleep(10000);
continue;
}
unsigned char *out_data = NULL;
int size = 0;
int frame_type = 0;
unsigned char *nv12_scale_data = NULL;
NV12Scale(h264_info.data, 1280, 720, &nv12_scale_data, process->getWidth(), process->getHeight());
if (my_h264enc)
size = my_h264enc->encode(my_h264enc,nv12_scale_data, &out_data,&frame_type);
if (process->encCallback())
process->encCallback()(out_data,size,frame_type);
if (process->start_record() && process->recordCallback())
process->recordCallback()(out_data,size,frame_type);
if (out_data)
free(out_data);
if (nv12_scale_data)
free(nv12_scale_data);
pthread_mutex_lock(&enc_mutex);
h264_info.get_data_end = 0;
pthread_mutex_unlock(&enc_mutex);
}
if (my_h264enc)
my_h264enc->unInit(my_h264enc);
ENCODE_LOG("%s(),%d\n", __func__,__LINE__);
return NULL;
}
H264Encoder::H264Encoder()
{
fd_ = nullptr;
start_enc_ = false;
start_record_ = false;
myH264EncInit();
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&enc_mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
}
H264Encoder::~H264Encoder()
{
}
int H264Encoder::startEnc(int width,int height,EncCallbackFunc encCallback)
{
if (start_enc_ == true)
return 0;
width_ = width;
height_ = height;
if (my_h264enc)
my_h264enc->init(my_h264enc,width, height);
encCallback_ = encCallback;
start_enc_ = true;
last_frame_ = false;
h264_info.get_data_end = 0;
memset(&h264_info,0,sizeof(h264_info));
createThread(encoderProcessThread,this);
return 0;
}
int H264Encoder::stopEnc(void)
{
if (start_enc_ == false)
return 0;
start_enc_ = false;
recordStop();
}
void H264Encoder::recordStart(EncCallbackFunc recordCallback)
{
if (start_record_ == true)
return;
recordCallback_ = recordCallback;
recordStopCallback_ = NULL;
start_record_ = true;
}
void H264Encoder::recordSetStopFunc(RecordStopCallbackFunc recordStopCallback)
{
recordStopCallback_ = recordStopCallback;
}
void H264Encoder::recordStop(void)
{
if (start_record_ == false)
return;
start_record_ = false;
if (recordStopCallback_)
recordStopCallback_();
recordStopCallback_ = NULL;
recordCallback_ = NULL;
}
bool H264Encoder::processFrame(std::shared_ptr<BufferBase> inBuf,
std::shared_ptr<BufferBase> outBuf)
{
if (start_enc_ == false) {
if (last_frame_ == false) {
last_frame_ = true;
goto post_frame;
}
return true;
}
post_frame:
if (h264_info.get_data_end == 0) {
h264_info.w = inBuf->getWidth();
h264_info.h = inBuf->getHeight();
memcpy(h264_info.data,inBuf->getVirtAddr(),inBuf->getDataSize());
pthread_mutex_lock(&enc_mutex);
h264_info.get_data_end = 1;
pthread_mutex_unlock(&enc_mutex);
}
return true;
}
<file_sep>/src/app/rdface/rd_face.c
/*
* =============================================================================
*
* Filename: rd_face.c
*
* Description: 阅面人脸识别算法
*
*
* Version: 1.0
* Created: 2019-06-18 19:34:21
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <arm_neon.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include "config.h"
#include "RSCommon.h"
#include "readsense_face_sdk.h"
#include "ion/ion.h"
#include "video_ion_alloc.h"
#include "thread_helper.h"
#include "rd_face.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define RECOGNIZE_INTAVAL 60
#define WIDTH_MAX 1280
#define HEIGHT_MAX 720
#define FACE_MODEL_PATH "/root/usr/face_model/"
#define APP_ID "dfe52c64a6a368bf181c76b512d2b3fe"
#define RECOGNITION_TIME 0
#define DPRINT(...) \
do { \
printf("\033[1;32m"); \
printf("[FACE->%s,%d]",__func__,__LINE__); \
printf(__VA_ARGS__); \
printf("\033[0m"); \
} while (0)
typedef struct _DebugInfo {
int opt;
const char *content;
}DebugInfo;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static const char* g_fd_weights_path = FACE_MODEL_PATH"fd.weights.bin";
static const char* g_fl_weights_path = FACE_MODEL_PATH"fl.weights.bin";
static const char* g_fle_light_weights_path = FACE_MODEL_PATH"fle_light.weights.bin";
static const char* g_fle_infrared_weights_path = FACE_MODEL_PATH"fle_infrared.weights.bin";
static const char* g_fgs_weights_path = FACE_MODEL_PATH"fgs.weights.bin";
static const char* g_fr_lite_weights_path = FACE_MODEL_PATH"fr_lite.weights.bin";
static const char* g_fq_weights_path = FACE_MODEL_PATH"fq.weights.bin";
static const char* g_fla_weights_path = FACE_MODEL_PATH"fla.weights.bin";
static const char* g_fags_weights_path = FACE_MODEL_PATH"fgas.weights.bin";
static struct video_ion model_ion;
static struct video_ion raw_ion;
static struct video_ion dst_ion;
static struct video_ion internal_ion;
static int dsp_fd;
static float feature_last[FACE_RECOGNITION_FEATURE_DIMENSION]; // 最后一次人脸特征值
static int track_id_last; // 最后一次人脸信息
static int recognize_intaval = 0; // 识别结果处理间隔
static int thread_start = 0;
static int thread_end = 1;
static void* threadTimer1s(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
thread_start = 1;
thread_end = 0;
while (thread_start) {
if (recognize_intaval)
recognize_intaval--;
sleep(1);
}
thread_end = 1;
return NULL;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rdfaceInit 初始化人脸识别算法
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
int rdfaceInit(void)
{
model_ion.fd = -1;
model_ion.client = -1;
DPRINT("=====into rdfaceInit()====\n");
if (video_ion_alloc_rational(&model_ion, 24 * 1024, 1024, 1, 1)) {
DPRINT("-----> model_ion alloc failed(24MB)\n");
goto exit;
}
DPRINT("==>>alloc model_ion.size:%d,(%dK) !!\n",model_ion.size,model_ion.size/1024);
raw_ion.fd = -1;
raw_ion.client = -1;
if (video_ion_alloc(&raw_ion, WIDTH_MAX, HEIGHT_MAX)) {
DPRINT("-----> raw_ion alloc failed(%dK)\n",WIDTH_MAX*HEIGHT_MAX/1024);
goto exit_model;
}
DPRINT("==>>alloc raw_ion.size:%d,(%dK)\n",raw_ion.size,raw_ion.size/1024);
dst_ion.fd = -1;
dst_ion.client = -1;
if (video_ion_alloc_rational(&dst_ion, 1024, 1024, 1, 1)) {
DPRINT("-----> dst_ion alloc failed(1MB)\n");
goto exit_raw;
}
DPRINT("==>>alloc dst_ion.size:%d,(%dK)\n",dst_ion.size,dst_ion.size/1024);
internal_ion.fd = -1;
internal_ion.client = -1;
if (video_ion_alloc_rational(&internal_ion, 1024, 1024, 1, 1)) {
DPRINT("-----> internal_ion alloc failed(1M)\n");
goto exit_dst;
}
DPRINT("==>>alloc internal_ion.size:%d,(%dK)\n",internal_ion.size,internal_ion.size/1024);
dsp_fd = open("/dev/dsp", O_RDWR);
if (dsp_fd < 0) {
DPRINT("------> opend dsp dev failed.\n");
goto exit_internal;
}
DPRINT("dsp face version_number: %s\n", readsense_face_sdk_get_version_number());
DPRINT("dsp face device_key: %s\n", readsense_face_sdk_get_device_key());
//初始化接口
if(readsense_initial_face_sdk(model_ion.buffer, 20, 5,
g_fd_weights_path, g_fl_weights_path,
g_fle_light_weights_path, g_fle_infrared_weights_path,
g_fgs_weights_path, 0,
g_fr_lite_weights_path, g_fq_weights_path,
0,g_fags_weights_path,
APP_ID,
// 2dfe86e156957ca1
// "ea15e2876d514524c873b6159b86f2f5d715819598ee3b116e51cb2338b8ffbe5556ef1d9e7ee21739588fd631923ffd80df7158e7e6fb561eac7faa8252f67e"
// f07440307d514cc7
g_config.f_license
// "424b15c4f0f7f373f7a893544bd758a95bda33c689ab124c66efdb9d93533afc5024f5c8abb68150991e642f54c8e13b34b8ed968aedd024d7d0bc72622ffedb"
)) {
DPRINT("%s:------> readsense_initial_face_sdk failed.\n", __func__);
goto exit_dsp;
}
DPRINT("=====exit rdfaceInit()====\n");
createThread(threadTimer1s,NULL);
return 0;
exit_dsp:
close(dsp_fd);
exit_internal:
video_ion_free(&internal_ion);
exit_dst:
video_ion_free(&dst_ion);
exit_raw:
video_ion_free(&raw_ion);
exit_model:
video_ion_free(&model_ion);
exit:
return -1;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rdfaceUninit 释放人脸识别算法资源
*/
/* ---------------------------------------------------------------------------*/
void rdfaceUninit(void)
{
thread_start = 0;
while(thread_end == 0) {
thread_start = 0;
usleep(10000);
}
close(dsp_fd);
video_ion_free(&internal_ion);
video_ion_free(&dst_ion);
video_ion_free(&raw_ion);
video_ion_free(&model_ion);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief fillFaceTrackBuf 填充图片数据
*
* @param image
* @param width
* @param height
*/
/* ---------------------------------------------------------------------------*/
static void fillFaceTrackBuf(unsigned char *image, int width, int height)
{
// DPRINT("face->width:%d height:%d\n",width,height);
raw_ion.width = width;
raw_ion.height = height;
raw_ion.size = width * height * 3 / 2;
memcpy(raw_ion.buffer, image, raw_ion.size);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief getFaceFeature 人脸特征提取
*
* @param image
* @param landmarks21[]
* @param outFRFeature 特征值
*
* @returns 0 成功 -1 失败
*/
/* ---------------------------------------------------------------------------*/
static int getFaceFeature(struct video_ion* image, rs_point landmarks21[] , float *outFRFeature)
{
float *pFRFeature = (float *)dst_ion.buffer;
#if RECOGNITION_TIME
struct timeval start_time,end_time;
float cost_time;
gettimeofday(&start_time,NULL);
#endif
//提取人脸特征值
if(readsense_face_recognition_lite(model_ion.buffer, (void*)model_ion.phys, image->buffer, (void*)image->phys,
dst_ion.buffer, (void*)dst_ion.phys, internal_ion.buffer, (void*)internal_ion.phys,
dsp_fd,image->width, image->height, (float *)landmarks21)){
DPRINT("%s:------> readsense_face_recognition_lite failed.\n", __func__);
return -1;
}
#if RECOGNITION_TIME
gettimeofday(&end_time,NULL);
cost_time = (1000000*end_time.tv_sec) + end_time.tv_usec - (1000000*start_time.tv_sec) - start_time.tv_usec;
DPRINT("recognition cost time: %f ms\n", cost_time / 1000);
#endif
memcpy(outFRFeature,pFRFeature,FACE_RECOGNITION_FEATURE_DIMENSION*sizeof(float));
return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rdfaceRegist 注册人脸
*
* @param image_buff 人脸图片,nv12格式
* @param w 图片宽
* @param h 图片高
* @param out_feature 返回特征值
*
* @returns 0成功 -1失败
*/
/* ---------------------------------------------------------------------------*/
int rdfaceRegist(unsigned char *image_buff,int w,int h,float **out_feature,int *out_feature_size)
{
DPRINT("in rdfaceRegist\n");
int *face_count = (int *)dst_ion.buffer;
RSFT_FACE_RESULT *pFace = (RSFT_FACE_RESULT *)((int *)dst_ion.buffer+1);
int ret;
if (w < 0 || w > 1280 || h < 0 || h > 720) {
return -1;
}
fillFaceTrackBuf(image_buff,w,h);
//人脸追踪,针对静态图片
ret = readsense_face_detection_and_landmark(model_ion.buffer, (void*)model_ion.phys,
raw_ion.buffer, (void*)raw_ion.phys, dst_ion.buffer, (void*)dst_ion.phys,
internal_ion.buffer, (void*)internal_ion.phys, dsp_fd, raw_ion.width, raw_ion.height);
if ( ret !=0 ) {
DPRINT("%s:------> readsense_face_detection_and_landmark LICENCE_VALIDATE_FAIL.\n", __func__);
return -1;
}
if (*face_count !=1 ) {
DPRINT("error : face num=%d\n",*face_count);
return -1;
}
DPRINT("\ntrackId: %d, blur: %f,front_prob:%f ,position is: [%d, %d, %d, %d] \n",
pFace->track_id, pFace->blur_prob, pFace->front_prob,
pFace->left, pFace->top, pFace->right, pFace->bottom);
//提特征
*out_feature = (float*)malloc(FACE_RECOGNITION_FEATURE_DIMENSION*sizeof(float));
*out_feature_size = FACE_RECOGNITION_FEATURE_DIMENSION*sizeof(float);
return getFaceFeature(&raw_ion, (rs_point *)pFace->face_landmark,*out_feature);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rdfaceRecognizer 探测并识别人脸
*
* @param image_buff 输入图像
* @param w 宽
* @param h 高
* @param featureCompare 人脸特征比较回调函数,回调中调用rdfaceGetFeatureSimilarity
*
* @returns 0 成功 -1 失败
*/
/* ---------------------------------------------------------------------------*/
int rdfaceRecognizer(unsigned char *image_buff,int w,int h,
int (*featureCompare)(float *feature,void *face_data_out,int gender,int age),void *face_data_out)
{
int *face_count = (int *)dst_ion.buffer;
RSFT_FACE_RESULT *pFace = (RSFT_FACE_RESULT *)((int *)dst_ion.buffer+1);
RSFT_FACE_RESULT *pFaceALL =NULL;
int ret = -1;
fillFaceTrackBuf(image_buff,w,h);
//人脸检测追踪,针对动态图像
int result = readsense_face_tracking(model_ion.buffer, (void*)model_ion.phys,
raw_ion.buffer, (void*)raw_ion.phys, dst_ion.buffer, (void*)dst_ion.phys,
internal_ion.buffer, (void*)internal_ion.phys, dsp_fd, raw_ion.width, raw_ion.height);
// DPRINT("\nreadsense_face_tracking return %d \n",result);
if ( result == RSFT_LICENCE_VALIDATE_FAIL ) {
DPRINT("%s:------> readsense_face_tracking LICENCE_VALIDATE_FAIL.\n", __func__);
goto exit;
}
// DPRINT("===>face num=%d\n",*face_count);
if (*face_count == 0) {
// DPRINT("error : face num=0\n");
goto exit;
}
int faceCount = *face_count;
pFaceALL = (RSFT_FACE_RESULT *)malloc(faceCount*sizeof(RSFT_FACE_RESULT));
if(pFaceALL==NULL) {
DPRINT("pFaceALL malloc error!\n");
goto exit;
}
memcpy(pFaceALL,pFace,faceCount*sizeof(RSFT_FACE_RESULT));
int i=0;
for(i=0; i<faceCount ; i++) {
float face_landmark[FACE_LANDMARK_NUM*2];
memcpy(face_landmark, pFaceALL[i].face_landmark, sizeof(face_landmark));
float *quality_value = (float *)dst_ion.buffer;
if(readsense_face_quality(model_ion.buffer,(void*)model_ion.phys,
raw_ion.buffer, (void*)raw_ion.phys,dst_ion.buffer, (void*)dst_ion.phys,
internal_ion.buffer, (void*)internal_ion.phys, dsp_fd, raw_ion.width, raw_ion.height,
face_landmark)) {
DPRINT("%s:------> readsense_face_quality failed.\n", __func__);
goto exit;
}
// DPRINT("==>quality_value:%f\n",*quality_value);
if(*quality_value < 0.25) {
// DPRINT("Low quality=%f\n",*quality_value);
continue;
}
if ((track_id_last == pFaceALL[i].track_id) && (track_id_last != 0)) {
continue;
}
track_id_last = pFaceALL[i].track_id;
float feature[FACE_RECOGNITION_FEATURE_DIMENSION];
//提取特征值
if (getFaceFeature(&raw_ion, (rs_point *)face_landmark,feature) != 0)
continue;
float sim = rdfaceGetFeatureSimilarity(feature_last,feature);
memcpy(feature_last,feature,sizeof(feature));
// printf("sim:%f,s:%f\n",sim , SIMILAYRITY );
if (sim > SIMILAYRITY || sim == 0) {
if (recognize_intaval == 0)
recognize_intaval = RECOGNIZE_INTAVAL;
else {
break;
}
}
// DPRINT("face_count:%d , facenum:%d: ,trackId: %d, blur: %f,front_prob:%f, gender:%d,age:%d,position is: [%d, %d, %d, %d] \n",
// faceCount,i,pFaceALL[i].track_id, pFaceALL[i].blur_prob, pFaceALL[i].front_prob,
// pFaceALL[i].gender , pFaceALL[i].age,
// pFaceALL[i].left, pFaceALL[i].top, pFaceALL[i].right, pFaceALL[i].bottom);
if (!featureCompare)
continue;
ret = featureCompare(feature,face_data_out,pFaceALL[i].gender,pFaceALL[i].age);
if (ret >= 0)
break;
}
exit:
free(pFaceALL);
// readsense_clear_tracking_state();
return ret;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rdfaceGetFeatureSimilarity 人脸特征对比,结果大于0.4,可以认为是
* 同一人,但最好取人脸库相识度最大的
*
* @param feature1
* @param feature2
*
* @returns 返回相似度 0-1之间,>0.4可以认为是同一人
*/
/* ---------------------------------------------------------------------------*/
float rdfaceGetFeatureSimilarity(float *feature1, float *feature2)
{
int i;
int dimension = FACE_RECOGNITION_FEATURE_DIMENSION;
int iter = dimension >> 5;
float32x4_t sum1 = vdupq_n_f32(0.0);
float32x4_t sum2 = vdupq_n_f32(0.0);
for (i = 0; i < iter; i++) {
float32x4_t f1_0 = vld1q_f32(feature1);
float32x4_t f2_0 = vld1q_f32(feature2);
sum1 = vaddq_f32(sum1, vmulq_f32(f1_0, f2_0));
float32x4_t f1_1 = vld1q_f32(feature1 + 4);
float32x4_t f2_1 = vld1q_f32(feature2 + 4);
sum2 = vaddq_f32(sum2, vmulq_f32(f1_1, f2_1));
float32x4_t f1_2 = vld1q_f32(feature1 + 8);
float32x4_t f2_2 = vld1q_f32(feature2 + 8);
sum1 = vaddq_f32(sum1, vmulq_f32(f1_2, f2_2));
float32x4_t f1_3 = vld1q_f32(feature1 + 12);
float32x4_t f2_3 = vld1q_f32(feature2 + 12);
sum2 = vaddq_f32(sum2, vmulq_f32(f1_3, f2_3));
float32x4_t f1_4 = vld1q_f32(feature1 + 16);
float32x4_t f2_4 = vld1q_f32(feature2 + 16);
sum1 = vaddq_f32(sum1, vmulq_f32(f1_4, f2_4));
float32x4_t f1_5 = vld1q_f32(feature1 + 20);
float32x4_t f2_5 = vld1q_f32(feature2 + 20);
sum2 = vaddq_f32(sum2, vmulq_f32(f1_5, f2_5));
float32x4_t f1_6 = vld1q_f32(feature1 + 24);
float32x4_t f2_6 = vld1q_f32(feature2 + 24);
sum1 = vaddq_f32(sum1, vmulq_f32(f1_6, f2_6));
float32x4_t f1_7 = vld1q_f32(feature1 + 28);
float32x4_t f2_7 = vld1q_f32(feature2 + 28);
sum2 = vaddq_f32(sum2, vmulq_f32(f1_7, f2_7));
feature1 += 32;
feature2 += 32;
}
sum1 = vaddq_f32(sum1, sum2);
return vgetq_lane_f32(sum1, 0) + vgetq_lane_f32(sum1, 1) + vgetq_lane_f32(sum1, 2) + vgetq_lane_f32(sum1, 3);
}
int rdfaceRecognizerOnce(unsigned char *image_buff,int w,int h,int *age,int *sex)
{
int *face_count = (int *)dst_ion.buffer;
RSFT_FACE_RESULT *pFace = (RSFT_FACE_RESULT *)((int *)dst_ion.buffer+1);
fillFaceTrackBuf(image_buff,w,h);
//人脸检测追踪,针对动态图像
int result = readsense_face_tracking(model_ion.buffer, (void*)model_ion.phys,
raw_ion.buffer, (void*)raw_ion.phys, dst_ion.buffer, (void*)dst_ion.phys,
internal_ion.buffer, (void*)internal_ion.phys, dsp_fd, raw_ion.width, raw_ion.height);
// DPRINT("\nreadsense_face_tracking return %d \n",result);
if ( result == RSFT_LICENCE_VALIDATE_FAIL ) {
DPRINT("%s:------> readsense_face_tracking LICENCE_VALIDATE_FAIL.\n", __func__);
return -1;
}
// DPRINT("===>face num=%d\n",*face_count);
if (*face_count == 0) {
// DPRINT("error : face num=0\n");
return -1;
}
*age = pFace->age;
*sex = pFace->gender;
return 0;
}
const char *rdfaceGetFaceVersion(void)
{
return readsense_face_sdk_get_version_number();
}
const char *rdfaceGetDeviceKey(void)
{
return readsense_face_sdk_get_device_key();
}
<file_sep>/src/gui/screen.c
/*
* =============================================================================
*
* Filename: screen.c
*
* Description: 窗口链表
*
* Version: 1.0
* Created: 2019-04-20 15:08:19
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "screen.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
ScreenForm Screen;
static void screenSetCurrent(const char *Class)
{
FormClass * form = Screen.head;
if(Class==NULL)
return ;
while(form) {
if(strncmp(Class,form->Class,15)==0) {
Screen.current = form;
// printf("[%s]%s\n", __FUNCTION__,Screen.current->Class);
break;
}
form = form->next;
}
}
static BOOL screenAddForm(HWND hWnd,const char *Class)
{
FormClass * Form = (FormClass *)malloc(sizeof(FormClass));
memset(Form,0,sizeof(FormClass));
Form->hWnd = hWnd;
strncpy(Form->Class,Class,15);
if(Screen.head == NULL) {
Screen.head = Screen.tail = Form;
} else {
Screen.tail->next = Form;
Screen.tail = Form;
}
Screen.Count++;
if(strcmp(Class,"Fvideo"))
screenSetCurrent(Class);
return TRUE;
}
//--------------------------------------------------------------------------
static BOOL screenDelForm(HWND hWnd)
{
FormClass * form,*parentform;
form = Screen.head;
while(form) {
if(form->hWnd != hWnd) {
parentform = form;
form = form->next;
continue;
}
// DBG_P("Form(%s)Del\n",form->Class);
if(Screen.head == form) {
Screen.head = form->next;
if(Screen.tail == form) Screen.tail = NULL;
} else {
parentform->next = form->next;
if(Screen.tail == form) Screen.tail = parentform;
}
free(form);
Screen.Count--;
return TRUE;
}
return FALSE;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief screenReturnMainForm 回到主界面
*/
/* ---------------------------------------------------------------------------*/
static void screenReturnMainForm(void)
{
int FormCnt=0;
HWND *Forms;
FormClass * form;
form = Screen.head;
Forms = (HWND *)calloc(sizeof(HWND),Screen.Count);
while(form && FormCnt<Screen.Count) {
//留下主窗口
if(strcmp(form->Class,"TFrmVL") && strcmp(form->Class,"Fvideo"))
Forms[FormCnt++] = form->hWnd;
form = form->next;
}
while(FormCnt) {
ShowWindow(Forms[FormCnt-1],SW_HIDE);
// SendMessage(Forms[FormCnt-1],MSG_CLOSE,0,-1);
FormCnt--;
}
free(Forms);
}
//--------------------------------------------------------------------------
static HWND screenFindForm(const char *Class)
{
FormClass * form = Screen.head;
if(Class==NULL)
return 0;
while(form) {
if(strncmp(Class,form->Class,15)==0)
return form->hWnd;
form = form->next;
}
return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief screenForeachForm 遍历所有窗口,发送消息
*
* @param Class
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static void screenForeachForm(int iMsg, WPARAM wParam, LPARAM lParam)
{
int FormCnt=0;
FormClass * form;
form = Screen.head;
while(form && FormCnt<Screen.Count) {
SendMessage(form->hWnd,iMsg,wParam,lParam);
form = form->next;
}
}
static HWND screenGetCurrent(void)
{
// printf("[%s]%s\n", __FUNCTION__,Screen.current->Class);
return Screen.current->hWnd;
}
void screenInit(void)
{
Screen.Add = screenAddForm;
Screen.Del = screenDelForm;
Screen.Find = screenFindForm;
Screen.ReturnMain = screenReturnMainForm;
Screen.foreachForm = screenForeachForm;
Screen.setCurrent = screenSetCurrent;
Screen.getCurrent = screenGetCurrent;
}
<file_sep>/src/gui/form_base.h
/*
* =====================================================================================
*
* Filename: FormBase.h
*
* Description: 设置类基本窗口框架
*
* Version: 1.0
* Created: 2016-02-19 15:24:17
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
#ifndef _FORM_BASE_H
#define _FORM_BASE_H
#include "commongdi.h"
#include "my_dialog.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define FORM_TIMER_1S 100 // 定时器1秒
#define FORM_SETTING_ONTIME 5 // 设置界面10秒无操作,则关闭窗口
enum {
FORM_STOP = 0,
FORM_CONTINUE = 1,
};
typedef struct _FormBasePriv {
char *name;
BITMAP *bmp_bkg;
MY_DLGTEMPLATE *dlgInitParam;
int idc_timer;
int auto_close_time; // 对话框自动关闭时间
int auto_close_time_set; // 对话框自动关闭时间设置(s),默认为FORM_SETTING_ONTIME
int show_video; // 界面是否显示视频
int (*dlgProc)(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
void (*initPara)(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
void (*callBack)(void);
}FormBasePriv;
typedef struct _FormBase {
FormBasePriv *priv;
int hDlg; // 当前对话框的句柄
int auto_close_time_set; // 对话框自动关闭时间设置,默认为FORM_SETTING_ONTIME
int (*baseProc)(struct _FormBase *this,HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
}FormBase;
FormBase * formBaseCreate(FormBasePriv *priv);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/module/singlechip/playvoice.c
/*
* =============================================================================
*
* Filename: playvoice.c
*
* Description: 播放音频
*
* Version: 1.0
* Created: 2019-07-27 12:29:55
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define DPRINT(...) \
do { \
printf("\033[1;34m"); \
printf("[UART->%s,%d]",__func__,__LINE__); \
printf(__VA_ARGS__); \
printf("\033[0m"); \
} while (0)
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
// static char cmd_buf[1024] = {0};
char * excuteCmd(char *Cmd,...)
{
int i;
FILE *fp;
int ret;
va_list argp;
char *argv;
char commond[512] = {0};
strcat(commond,Cmd);
va_start( argp, Cmd);
for(i=1;i<20;i++) {
argv = va_arg(argp,char *);
if(argv == NULL)
break;
strcat(commond," ");
strcat(commond,argv);
}
va_end(argp);
DPRINT("cmd :%s\n",commond);
#if 0
if ((fp = popen(commond, "r") ) == 0) {
perror("popen");
return NULL;
}
memset(cmd_buf,0,sizeof(cmd_buf));
ret = fread( cmd_buf, sizeof(cmd_buf), sizeof(char), fp ); //将刚刚FILE* stream的数据流读取到cmd_buf
// DPRINT("r:%d\n",ret );
if ( (ret = pclose(fp)) == -1 ) {
DPRINT("close popen file pointer fp error!\n");
}
return cmd_buf;
#else
// 用此函数导致产生僵尸进程
system(commond);
return 0;
#endif
}
int playVoice(char * file_name)
{
excuteCmd("/data/play.sh",file_name,NULL);
}
<file_sep>/src/wireless/my_dns.c
/*
* =============================================================================
*
* Filename: Dns.c
*
* Description: 域名解析
*
* Version: 1.0
* Created: 2016-06-27 15:29:08
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <setjmp.h>
#include <errno.h>
#include "debug.h"
#include "my_dns.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
int dnsGetIp(char *domain_name,char *ip)
{
#if 0
struct hostent *host;
struct sockaddr_in dest_addr;
unsigned long inaddr=0l;
if( (inaddr = inet_addr(domain_name)) == INADDR_NONE) {
if((host=gethostbyname(domain_name) ) == NULL) {
perror("gethostbyname error");
return -1;
}
memcpy( (char *)&dest_addr.sin_addr,host->h_addr,host->h_length);
memcpy( ip,inet_ntoa(dest_addr.sin_addr),strlen(inet_ntoa(dest_addr.sin_addr)));
} else {
memcpy( ip,domain_name,strlen(domain_name));
}
return 0;
#else
struct addrinfo * res, *pt;
struct sockaddr_in *sinp;
struct in_addr addr1;
const char *addr;
char abuf[INET_ADDRSTRLEN];
int succ=0,i=0;
if (strncmp("http://",domain_name,strlen("http://")) == 0) {
domain_name += strlen("http://");
} else if (strncmp("https://",domain_name,strlen("https://")) == 0) {
domain_name += strlen("https://");
}
if (inet_pton(AF_INET, ip, &addr1) <= 0) {
succ = getaddrinfo(domain_name, NULL, NULL, &res);
if(succ != 0) {
printf("dns fail,%s\n",domain_name );
return -1;
}
for(pt=res, i=0; pt != NULL; pt=pt->ai_next, i++){
sinp = (struct sockaddr_in *)pt->ai_addr;
addr = inet_ntop(AF_INET, &sinp->sin_addr, abuf, INET_ADDRSTRLEN);
// printf("%2d. IP=%s\n", i, addr);
}
} else {
addr = domain_name;
}
memcpy(ip,addr,strlen(addr));
return 0;
#endif
}
<file_sep>/src/wireless/udp_server.c
/*
* =============================================================================
*
* Filename: UDPServer.c
*
* Description: udp驱动
*
* Version: 1.0
* Created: 2018-03-05 17:33:54
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <sys/prctl.h>
#include "debug.h"
#include "queue.h"
#include "udp_server.h"
#include "externfunc.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define UDP_PACKET_MAX 2500 //UDP包最大长度,与协议保持一致
#define TASKTIMEOUT (50) // 任务发送间隔 ms
#define MAXLIST (50) // 最大任务数量
typedef struct _UdpThreadOps {
int m_socket; //套接字
int port; //端口号
int Terminated; //是否中止线程
}UdpThreadOps;
typedef struct _UdpSendLists {
char IP[16];
int Port;
void *pData;
int Size;
int Times;
int SendTimes;
CallBackUDP Func;
void *CallBackData;
} UdpSendLists;
typedef struct _UdpServerPriv {
pthread_t pthread_server; // 服务线程
pthread_t pthread_receive;// 接收线程
pthread_mutex_t mutex; //队列控制互斥信号
UdpSendLists Lists[MAXLIST];
int ListCnt;
struct _UdpThreadOps * control;
Queue *socket_queue;
}UdpServerPriv;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
TUDPServer *udp_server;
/* ---------------------------------------------------------------------------*/
/**
* @brief getDiffSysTick 计算32位差值
*
* @param new
* @param old
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static uint32_t getDiffSysTick(uint64_t new,uint64_t old)
{
uint32_t diff;
if (new >= old)
diff = new - old;
else
diff = 0XFFFFFFFF - old + new;
return diff;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpServerGetTickCount 返回系统tick
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static unsigned long long udpServerGetTickCount(void)
{
// return GetTickCount(); // 用此函数不能返回精准毫秒数
return getMs();
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpServerDelayMs 延时ms
*
* @param ms 毫秒
*/
/* ---------------------------------------------------------------------------*/
static void udpServerDelayMs(int ms)
{
usleep(ms * 1000);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpServerPostMessage 发送侦听到的消息到各个窗口或线程
*
* @param ABinding
* @param AData
*/
/* ---------------------------------------------------------------------------*/
static void udpServerPostMessage(
TUDPServer* This,
SocketHandle *ABinding,
SocketPacket *AData)
{
UdpSocket socket_data;
socket_data.ABinding = ABinding;
socket_data.AData = AData;
This->priv->socket_queue->post(This->priv->socket_queue,&socket_data);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpServerTaskSend 发送task任务
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void udpServerTaskSend(TUDPServer* This,uint64_t *dwLastTick)
{
int i;
uint64_t dwTick = udpServerGetTickCount();
if(getDiffSysTick(dwTick,*dwLastTick) <= TASKTIMEOUT)
return;
*dwLastTick = dwTick;
pthread_mutex_lock (&This->priv->mutex); //加锁
for(i=0;i<MAXLIST;i++) {
UdpSendLists *pList = &This->priv->Lists[i];
if(!pList->pData)
continue;
if(pList->SendTimes < pList->Times) {
// 重发指定次数
This->SendBuffer(This,pList->IP,pList->Port,pList->pData,pList->Size);
pList->SendTimes++;
// printf("times:%d,UDP Send IP:%s:%d,size:%d\n",pList->SendTimes,pList->IP,pList->Port,pList->Size );
} else {
// printf("send time out:%d,UDP Send IP:%s:%d,size:%d\n",pList->SendTimes,pList->IP,pList->Port,pList->Size );
// 重发指定次数后失败
if(pList->Func)
pList->Func(MSG_SENDTIMEOUT,pList->CallBackData);
free(pList->pData);
pList->pData = NULL;
This->priv->ListCnt--;
}
}
pthread_mutex_unlock (&This->priv->mutex); //解锁
}
//---------------------------------------------------------------------------
// UDP Server监听数据线程
//---------------------------------------------------------------------------
static void udpServerRecvData(TUDPServer* This,
SocketPacket *AData,
struct sockaddr_in *from,
int fromlen)
{
SocketHandle *ABinding;
ABinding = (SocketHandle*)calloc(1,sizeof(SocketHandle));
if(ABinding == NULL) {
free(AData);
printf("udp server No Memory alloc ABinding\n");
return;
}
memset(ABinding,0,sizeof(SocketHandle));
ABinding->Port = htons(from->sin_port);
char *pTmp = inet_ntoa(from->sin_addr);
if(pTmp)
strcpy(ABinding->IP,pTmp);
udpServerPostMessage(This,ABinding,AData);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpServerThread udp服务线程
*
* @param ThreadData
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static void * udpServerThread(void *ThreadData)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
// socklen_t addrlen;
TUDPServer *This = (TUDPServer *)ThreadData;
UdpThreadOps *control = This->priv->control;
struct timeval timeout;
fd_set fdR;
uint64_t dwLastTick = udpServerGetTickCount();
while(!control->Terminated)
{
FD_ZERO(&fdR);
FD_SET(control->m_socket, &fdR);
timeout.tv_sec=0;
timeout.tv_usec=50000; //50ms
// usleep(10000);
switch (select(control->m_socket+1, &fdR,NULL, NULL, &timeout))
{
case -1:
printf("udp server select err!\n");
// This->SendBuffer(This,Public.center_msg[0].IP,UDPSERVER_PORT,err,strlen(err));
// goto error; 20180111 xb 不能退出,
break;
case 0: // 未收到数据,udp服务发送task任务,间隔时间 TASKTIMEOUT
udpServerTaskSend(This,&dwLastTick);
break;
default: // 收到数据,处理数据
if(FD_ISSET(control->m_socket,&fdR)) {
struct sockaddr_in from;
SocketPacket *AData = (SocketPacket *)calloc(1,UDP_PACKET_MAX);
int fromlen = sizeof(struct sockaddr_in);
memset(&from,0,sizeof(from));
if(AData == NULL) {
printf("UDP Server No Memory alloc\n");
break;
}
AData->Size=recvfrom(control->m_socket,
AData->Data,
UDP_PACKET_MAX-4,
MSG_NOSIGNAL,
(struct sockaddr*)&from,
(socklen_t *)&fromlen);
if(AData->Size > 0)
udpServerRecvData(This,AData,&from,fromlen);
else
free(AData);
} else
udpServerDelayMs(1);
//为防止接收阻塞发送任务,同时也继续发送task任务,
udpServerTaskSend(This,&dwLastTick);
break;
}
}
error:
printf("UDP Server Thread Exit\n");
control->Terminated = 1;
free(control);
pthread_exit(NULL);
return NULL;
}
static void udpServerDestroy(TUDPServer *This)
{
This->priv->control->Terminated = 1;
close(This->priv->control->m_socket);
free(This);
}
static int udpServerGetSocket(TUDPServer *This)
{
return This->priv->control->m_socket;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpServerSendBuffer 直接发送数据
*
* @param This
* @param IP
* @param port
* @param pBuf
* @param size
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int udpServerSendBuffer(TUDPServer *This,const char *IP,int port,const void *pBuf,int size)
{
struct sockaddr_in *p;
struct sockaddr addr;
struct hostent *hostaddr;
if(This->priv->control->m_socket<0) {
return -1;
}
if(IP[0]==0 || port==0) {
return -2;
}
memset(&addr,0,sizeof(addr));
p=(struct sockaddr_in *)&addr;
p->sin_family=AF_INET;
p->sin_port=htons(port);
if(IP[0]<'0' || IP[0]>'9') {
hostaddr = gethostbyname(IP);
if(!hostaddr) {
printf("ERR hostaddr,IP:%s\n",IP );
return -3;
}
memcpy(&p->sin_addr,hostaddr->h_addr,hostaddr->h_length);
} else {
p->sin_addr.s_addr = inet_addr(IP);
if( (p->sin_addr.s_addr == INADDR_NONE)
&& (strcmp(IP,"255.255.255.255") != 0) ) {
printf("ERR INADDR_NONE,IP:%s\n",IP );
return -4;
}
}
return sendto(This->priv->control->m_socket,
(char*)pBuf,
size,
MSG_NOSIGNAL,
&addr,
sizeof(struct sockaddr_in));
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpServerRecvBuffer 接收数据
*
* @param This
* @param pBuf
* @param size
* @param TimeOut
* @param from
* @param fromlen
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int udpServerRecvBuffer(TUDPServer *This,void *pBuf,int size,int TimeOut,
void * from,int * fromlen)
{
int iRet;
struct timeval timeout;
fd_set fdR;
if(This->priv->control->m_socket<0)
return -1;
if(TimeOut <0) {
iRet = recvfrom(This->priv->control->m_socket,
(char*)pBuf,
size,
MSG_NOSIGNAL,
(struct sockaddr *)from,
(socklen_t *)fromlen);
return iRet;
} else {
FD_ZERO(&fdR);
FD_SET(This->priv->control->m_socket, &fdR);
timeout.tv_sec=TimeOut / 1000;
timeout.tv_usec=(TimeOut % 1000)*1000;
if(select(This->priv->control->m_socket+1, &fdR,NULL, NULL, &timeout)<=0)
return -1;
iRet = recvfrom(This->priv->control->m_socket,
(char*)pBuf,
size,
MSG_NOSIGNAL,
(struct sockaddr *)from,
(socklen_t *)fromlen);
return iRet;
}
}
//---------------------------------------------------------------------------
static int udpServerTerminated(TUDPServer *This)
{
return This->priv->control->Terminated;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpServerAddTask 通过添加任务发送数据
*
* @param This
* @param IP
* @param Port
* @param pData
* @param Size
* @param Times
* @param Func
* @param CallBackData
*/
/* ---------------------------------------------------------------------------*/
static void udpServerAddTask(TUDPServer* This,
const char *IP,
int Port,
void *pData,
int Size,
int Times,
CallBackUDP Func,
void *CallBackData)
{
int idx;
while(This->priv->ListCnt > MAXLIST) {
printf("Server task out!! cnt:%d\n",This->priv->ListCnt );
udpServerDelayMs(100);
}
pthread_mutex_lock (&This->priv->mutex); //加锁
//搜索空闲任务位置
for(idx=0;idx<MAXLIST;idx++) {
if(This->priv->Lists[idx].pData==NULL)
break;
}
//添加任务
if(idx<MAXLIST) {
This->priv->Lists[idx].pData = calloc(1,Size);
memcpy(This->priv->Lists[idx].pData,pData,Size);
strcpy(This->priv->Lists[idx].IP,IP);
This->priv->Lists[idx].Port = Port;
This->priv->Lists[idx].Size = Size;
This->priv->Lists[idx].SendTimes = 0;
This->priv->Lists[idx].Times = Times;
This->priv->Lists[idx].Func = Func;
This->priv->Lists[idx].CallBackData = CallBackData;
This->priv->ListCnt++;
// printf("add task id:%d,cnt:%d\n",idx,This->priv->ListCnt );
} else {
printf("ERR idx:%d\n",idx );
}
pthread_mutex_unlock (&This->priv->mutex); //解锁
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpServerKillTask删除任务
*
* @param This
* @param IP
* @param Port
*/
/* ---------------------------------------------------------------------------*/
static void udpServerKillTask(TUDPServer* This,const char *IP,int Port)
{
int i;
pthread_mutex_lock (&This->priv->mutex); //加锁
for(i=0;i<MAXLIST;i++) {
UdpSendLists *pList = &This->priv->Lists[i];
if(pList->pData && strcmp(pList->IP,IP)==0 && pList->Port==Port) {
free(pList->pData);
pList->pData = NULL;
This->priv->ListCnt--;
}
}
pthread_mutex_unlock (&This->priv->mutex); //解锁
}
static int udpServerKillTaskCondition(TUDPServer* This,
int (*condition)(void *arg1,void *arg2),void *arg)
{
int i;
for(i=0;i<MAXLIST;i++) {
UdpSendLists *pList = &This->priv->Lists[i];
if(pList->pData == NULL)
continue;
if (condition(pList->pData,arg)) {
if(pList->Func)
pList->Func(MSG_SENDSUCCESS,pList->CallBackData);
free(pList->pData);
pList->pData = NULL;
This->priv->ListCnt--;
break;
}
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpSocketReadThread 侦听端口数据接收线程
*
* @param arg
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static void *udpSocketReadThread(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
UdpSocket socket_data;
TUDPServer *udp = (TUDPServer*)arg;
// 阻塞状态 不需要延时
while (1) {
udp->priv->socket_queue->get(udp->priv->socket_queue,&socket_data);
if (udp->udpSocketRead)
udp->udpSocketRead(socket_data.ABinding,socket_data.AData);
free(socket_data.ABinding);
free(socket_data.AData);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpServerCreate 创建一个线程,监听指定的端口
*
* @param Handle
* @param Port
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
TUDPServer* udpServerCreate(int Port,const char *queue_name)
{
int ret;
int opt = 1;
pthread_attr_t threadAttr1; //线程属性
int trueval = 1;
struct sockaddr_in local_addr;
pthread_mutexattr_t mutexattr;
TUDPServer* This;
This = (TUDPServer *)calloc(1,sizeof(TUDPServer));
if(This==NULL) {
printf("alloc UDPServer memory failt!\n");
goto error;
}
This->priv = (UdpServerPriv*)calloc(1,sizeof(UdpServerPriv));
if(This->priv==NULL) {
printf("alloc udp priv memory fail!\n");
goto error;
}
This->priv->control =(struct _UdpThreadOps*)calloc(1,sizeof(struct _UdpThreadOps));
if(This->priv->control==NULL) {
printf("alloc control memory fail!\n");
goto error;
}
This->priv->control->port = Port;
This->priv->control->Terminated = 0;
pthread_mutexattr_init(&mutexattr);
/* Set the mutex as a recursive mutex */
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
/* create the mutex with the attributes set */
pthread_mutex_init(&This->priv->mutex, &mutexattr);
/* destroy the attribute */
pthread_mutexattr_destroy(&mutexattr);
memset(&local_addr,0,sizeof(local_addr));
//初始化套接字
This->priv->control->m_socket=socket(AF_INET,SOCK_DGRAM,0);
if(This->priv->control->m_socket < 0) {
printf("UDP Server init socket failed!\n");
goto error;
}
ret = setsockopt(This->priv->control->m_socket,SOL_SOCKET,SO_BROADCAST,(char*)&opt,sizeof(opt));
if(ret != 0) {
printf("setsockopt server error %d\n",ret);
}
//绑定套接字
local_addr.sin_family = AF_INET;
local_addr.sin_port = htons(Port);
local_addr.sin_addr.s_addr = INADDR_ANY;
if(bind(This->priv->control->m_socket, (struct sockaddr *)&local_addr, sizeof(struct sockaddr))<0) {
printf("bind to port failed!\n");
close(This->priv->control->m_socket);
goto error;
}
//在程序关闭后可以立即使用该端口
setsockopt(This->priv->control->m_socket,SOL_SOCKET,SO_REUSEADDR,&trueval,sizeof(trueval));
This->priv->socket_queue = queueCreate(queue_name,QUEUE_BLOCK,sizeof(UdpSocket));
This->Destroy = udpServerDestroy;
This->RecvBuffer = udpServerRecvBuffer;
This->SendBuffer = udpServerSendBuffer;
This->AddTask = udpServerAddTask;
This->KillTaskCondition = udpServerKillTaskCondition;
pthread_attr_init(&threadAttr1); //附加参数
pthread_attr_setdetachstate(&threadAttr1,PTHREAD_CREATE_DETACHED); //设置线程为自动销毁
pthread_create(&(This->priv->pthread_server),&threadAttr1,udpServerThread,This); //创建线程
pthread_attr_destroy(&threadAttr1); //释放附加参数
pthread_attr_init(&threadAttr1);
pthread_attr_setdetachstate(&threadAttr1,PTHREAD_CREATE_DETACHED);
pthread_create(&(This->priv->pthread_receive),&threadAttr1,udpSocketReadThread,This);
pthread_attr_destroy(&threadAttr1);
return This;
error:
if(This && This->priv->control)
free(This->priv->control);
if(This)
free(This);
return NULL;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpServerInit 初始化udp服务
*
* @param port 侦听端口
*/
/* ---------------------------------------------------------------------------*/
void udpServerInit(void (*udpSocketRead)(SocketHandle *ABinding,SocketPacket *AData),
int port)
{
udp_server = udpServerCreate(port,"udp_server");
if (udp_server)
udp_server->udpSocketRead = udpSocketRead;
}
<file_sep>/src/app/my_video.c
/*
* =============================================================================
*
* Filename: my_video.c
*
* Description: 视频接口
*
* Version: 1.0
* Created: 2019-06-19 10:19:50
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "debug.h"
#include "jpeg_enc_dec.h"
#include "media_muxer.h"
#include "my_face.h"
#include "state_machine.h"
#include "ucpaas/ucpaas.h"
#include "sql_handle.h"
#include "protocol.h"
#include "externfunc.h"
#include "thread_helper.h"
#include "timer.h"
#include "config.h"
#include "my_video.h"
#include "my_mixer.h"
#include "my_audio.h"
#include "my_gpio.h"
#include "video/video_server.h"
#include "share_memory.h"
#include "my_update.h"
#include "form_videolayer.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
extern void resetAutoSleepTimerLong(void);
extern void resetAutoSleepTimerShort(void);
extern int formCreateCaputure(int count);
extern void topMsgCammerError(void);
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define IAMGE_MAX_W 1280
#define IAMGE_MAX_H 720
#define IMAGE_MAX_DATA (IAMGE_MAX_W * IAMGE_MAX_H * 3 / 2 )
#define TIME_TALKING 180
#define TIME_CALLING 30
#define TIME_RECORD 30
enum {
EV_FACE_ON, // 打开人脸识别功能
EV_FACE_OFF_FINISH, // 关闭人脸识别功能结束
EV_FACE_REGIST, // 注册人脸
EV_FACE_RECOGNIZER, // 识别人脸
EV_TALK_CALLOUT, // 对讲呼出
EV_TALK_CALLOUTALL, // 遍历对讲呼出
EV_TALK_CALLOUTOK, // 对讲呼出成功
EV_TALK_CALLIN, // 对讲呼入
EV_TALK_ANSWER, // 对讲接听
EV_TALK_HANGUP, // 对讲挂机
EV_TALK_HANGUPALL, // 遍历对讲挂机
EV_CAPTURE, // 截图
EV_RECORD_START, // 录像开始
EV_RECORD_STOP, // 录像结束
EV_RECORD_STOP_FINISHED,// 录像结束后执行动作
EV_DELAY_SLEEP, // APP操作时延长睡眠时间
EV_UPDATE, // 升级软件
EV_UPDATE_FINISH, // 升级完成
};
enum {
ST_IDLE, // 空闲状态
ST_FACE, // 人脸识别开启状态
ST_FACEOFF_RECORD, // 人脸识别关闭过程,之后开始录像
ST_TALK_CALLOUT,// 对讲呼出状态
ST_TALK_CALLOUTALL,// 遍历对讲呼出状态
ST_TALK_CALLIN, // 对讲呼入状态
ST_TALK_TALKING,// 对讲中状态
ST_RECORDING, // 录像状态
ST_RECORD_STOPPING,// 录像停止状态
ST_UPDATE, // 升级状态
};
enum {
DO_FAIL, // 信息发送失败
DO_NOTHING, // 不做任何操作
DO_FACE_ON, // 人脸识别开启
DO_FACE_OFF, // 人脸识别关闭
DO_FACE_REGIST, // 注册人脸
DO_FACE_RECOGNIZER, // 识别人脸
DO_TALK_CALLOUT, // 对讲呼出
DO_TALK_CALLOUTALL, // 遍历对讲呼出
DO_TALK_CALLIN, // 对讲呼入
DO_TALK_ANSWER, // 对讲接听
DO_TALK_HANGUP, // 对讲挂机
DO_TALK_HANGUPALL, // 遍历对讲挂机
DO_CAPTURE, // 抓拍本地
DO_CAPTURE_NO_UI, // 抓拍本地,不进入抓拍界面
DO_RECORD_START, // 录像开始
DO_RECORD_STOP, // 录像结束
DO_DELAY_SLEEP, // APP操作时延长睡眠时间
DO_UPDATE, // 执行升级操作
};
enum {
CALL_RESULT_NO, // 未得到呼叫结果或已处理过呼叫结果
CALL_RESULT_SUCCESS, // 呼叫成功
CALL_RESULT_FAIL, // 呼叫失败
};
typedef struct _StmData {
int type;
int call_dir; // 操作方向 0 本机,1对方
int cap_count; // 抓拍照片数量
int cap_type; // 抓拍类型
char nick_name[128];
char usr_id[128];
// 升级使用
char ip[16];
int port;
char file_path[512];
enum HangupType hangup_type;
}StmData;
typedef struct _TalkPeerDev {
char peer_nick_name[128];
int call_out_result;
int call_time;
int type;
}TalkPeerDev;
typedef struct _StmDo {
int action;
int (*proc)(void *data,MyVideo *arg);
}StmDo;
typedef struct _CapData {
uint64_t pic_id;
int count; // 抓拍照片数量
int video_count; // 录像数量,仅针对通话时多次录像
char file_date[32];
char file_name[32];
char nick_name[128];
char usr_id[128];
}CapData;
typedef struct _CammerData {
int get_data_end;
int type;
int w,h;
char data[IMAGE_MAX_DATA];
}CammerData;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
MyVideo *my_video;
static char *st_debug_ev[] = {
"EV_FACE_ON", // 打开人脸识别功能
"EV_FACE_OFF_FINISH", // 关闭人脸识别功能结束
"EV_FACE_REGIST", // 注册人脸
"EV_FACE_RECOGNIZER", // 识别人脸
"EV_TALK_CALLOUT", // 对讲呼出
"EV_TALK_CALLOUTALL", // 遍历对讲呼出
"EV_TALK_CALLOUTOK", // 对讲呼出成功
"EV_TALK_CALLIN", // 对讲呼入
"EV_TALK_ANSWER", // 对讲接听
"EV_TALK_HANGUP", // 对讲挂机
"EV_TALK_HANGUPALL", // 遍历对讲挂机
"EV_CAPTURE", // 截图
"EV_RECORD_START", // 录像开始
"EV_RECORD_STOP", // 录像结束
"EV_RECORD_STOP_FINISHED",// 录像结束后执行动作
"EV_DELAY_SLEEP", // APP操作时延长睡眠时间
"EV_UPDATE", // 升级软件
"EV_UPDATE_FINISH", // 升级完成
};
static char *st_debug_st[] = {
"ST_IDLE",
"ST_FACE",
"ST_FACEOFF_RECORD", // 人脸识别关闭过程,之后开始录像
"ST_TALK_CALLOUT",
"ST_TALK_CALLOUTALL",
"ST_TALK_CALLIN",
"ST_TALK_TALKING",
"ST_RECORDING",
"ST_RECORD_STOPPING",
"ST_UPDATE", // 升级状态
};
static char *st_debug_do[] = {
"DO_FAIL",
"DO_NOTHING",
"DO_FACE_ON",
"DO_FACE_OFF",
"DO_FACE_REGIST",
"DO_FACE_RECOGNIZER",
"DO_TALK_CALLOUT",
"DO_TALK_CALLOUTALL",
"DO_TALK_CALLIN",
"DO_TALK_ANSWER",
"DO_TALK_HANGUP",
"DO_TALK_HANGUPALL", // 遍历对讲挂机
"DO_CAPTURE",
"DO_CAPTURE_NO_UI",
"DO_RECORD_START",
"DO_RECORD_STOP",
"DO_DELAY_SLEEP", // APP操作时延长睡眠时间
"DO_UPDATE", // 执行升级操作
};
static StateTableDebug st_debug = {
.ev = st_debug_ev,
.st = st_debug_st,
.todo = st_debug_do,
};
static StmData *st_data = NULL;
static StMachine* stm;
static CapData cap_data;
static MPEG4Head* avi = NULL;
static ReportTalkData talk_data;
static TalkPeerDev talk_peer_dev; // 对讲对方信息
static pthread_mutex_t mutex;
static ShareMemory *share_mem = NULL; //共享内存
static int send_video_start = 0;
static int record_state = 0; // 1录像状态 0非录像状态
static int record_time = 0; // 录像倒计时时间
static StateTable state_table[] =
{
// 人脸开启,注册,识别
{EV_FACE_ON, ST_IDLE, ST_FACE, DO_FACE_ON},
{EV_FACE_REGIST, ST_FACE, ST_FACE, DO_FACE_REGIST},
{EV_FACE_RECOGNIZER,ST_FACE, ST_FACE, DO_FACE_RECOGNIZER},
// 关闭人脸时,根据当前不同状态,做不同操作
{EV_FACE_OFF_FINISH,ST_TALK_CALLOUT, ST_TALK_CALLOUT, DO_TALK_CALLOUT},
{EV_FACE_OFF_FINISH,ST_TALK_CALLOUTALL, ST_TALK_CALLOUTALL, DO_TALK_CALLOUTALL},
{EV_FACE_OFF_FINISH,ST_TALK_CALLIN, ST_TALK_CALLIN, DO_TALK_CALLIN},
{EV_FACE_OFF_FINISH,ST_FACEOFF_RECORD, ST_RECORDING, DO_RECORD_START},
{EV_FACE_OFF_FINISH,ST_UPDATE, ST_UPDATE, DO_UPDATE},
{EV_TALK_CALLOUT, ST_IDLE, ST_TALK_CALLOUT, DO_TALK_CALLOUT},
{EV_TALK_CALLOUT, ST_FACE, ST_TALK_CALLOUT, DO_FACE_OFF},
{EV_TALK_CALLOUT, ST_TALK_CALLOUTALL, ST_TALK_CALLOUTALL, DO_TALK_CALLOUT},
{EV_TALK_CALLOUTALL,ST_IDLE, ST_TALK_CALLOUTALL, DO_TALK_CALLOUTALL},
{EV_TALK_CALLOUTALL,ST_FACE, ST_TALK_CALLOUTALL, DO_FACE_OFF},
{EV_TALK_CALLOUTOK, ST_TALK_CALLOUTALL, ST_TALK_CALLOUT, DO_NOTHING},
{EV_TALK_CALLIN, ST_IDLE, ST_TALK_CALLIN, DO_TALK_CALLIN},
{EV_TALK_CALLIN, ST_FACE, ST_TALK_CALLIN, DO_FACE_OFF},
{EV_TALK_ANSWER, ST_TALK_CALLIN, ST_TALK_TALKING, DO_TALK_ANSWER},
{EV_TALK_ANSWER, ST_TALK_CALLOUT, ST_TALK_TALKING, DO_TALK_ANSWER},
{EV_TALK_ANSWER, ST_TALK_CALLOUTALL, ST_TALK_TALKING, DO_TALK_ANSWER},
{EV_TALK_HANGUP, ST_TALK_CALLOUT, ST_IDLE, DO_TALK_HANGUP},
{EV_TALK_HANGUP, ST_TALK_CALLIN, ST_IDLE, DO_TALK_HANGUP},
{EV_TALK_HANGUP, ST_TALK_TALKING, ST_IDLE, DO_TALK_HANGUP},
{EV_TALK_HANGUP, ST_TALK_CALLOUTALL, ST_TALK_CALLOUTALL, DO_TALK_HANGUPALL},
{EV_TALK_HANGUPALL, ST_TALK_CALLOUTALL, ST_IDLE, DO_TALK_HANGUP},
{EV_RECORD_START, ST_IDLE, ST_RECORDING, DO_RECORD_START},
{EV_RECORD_START, ST_FACE, ST_FACEOFF_RECORD, DO_FACE_OFF},
{EV_RECORD_START, ST_TALK_CALLIN, ST_TALK_CALLIN, DO_RECORD_START},
{EV_RECORD_START, ST_TALK_CALLOUT, ST_TALK_CALLOUT, DO_RECORD_START},
{EV_RECORD_START, ST_TALK_TALKING, ST_TALK_TALKING, DO_RECORD_START},
{EV_RECORD_STOP, ST_RECORDING, ST_RECORD_STOPPING, DO_RECORD_STOP},
{EV_RECORD_STOP, ST_TALK_CALLIN, ST_TALK_CALLIN, DO_RECORD_STOP},
{EV_RECORD_STOP, ST_TALK_CALLOUT, ST_TALK_CALLOUT, DO_RECORD_STOP},
{EV_RECORD_STOP, ST_TALK_TALKING, ST_TALK_TALKING, DO_RECORD_STOP},
{EV_RECORD_STOP_FINISHED, ST_RECORD_STOPPING, ST_FACE, DO_FACE_ON},
{EV_CAPTURE, ST_IDLE, ST_IDLE, DO_CAPTURE},
{EV_CAPTURE, ST_FACE, ST_FACE, DO_CAPTURE},
{EV_CAPTURE, ST_TALK_TALKING, ST_TALK_TALKING, DO_CAPTURE_NO_UI},
{EV_CAPTURE, ST_TALK_CALLOUT, ST_TALK_CALLOUT, DO_CAPTURE_NO_UI},
{EV_CAPTURE, ST_TALK_CALLOUTALL, ST_TALK_CALLOUTALL, DO_CAPTURE_NO_UI},
{EV_CAPTURE, ST_TALK_CALLIN, ST_TALK_CALLIN, DO_CAPTURE_NO_UI},
{EV_DELAY_SLEEP,ST_IDLE, ST_IDLE, DO_DELAY_SLEEP},
{EV_DELAY_SLEEP,ST_FACE, ST_FACE, DO_DELAY_SLEEP},
{EV_UPDATE, ST_FACE, ST_UPDATE, DO_FACE_OFF},
{EV_UPDATE, ST_IDLE, ST_UPDATE, DO_UPDATE},
};
static int stmDoFail(void *data,MyVideo *arg)
{
int msg = *(int *)data;
switch (msg)
{
case DO_FACE_ON:
break;
case DO_FACE_OFF:
break;
default:
break;
}
printf("%s()%s\n",__func__,st_debug_ev[msg]);
}
static int stmDoNothing(void *data,MyVideo *arg)
{
}
static int stmDoFaceOn(void *data,MyVideo *arg)
{
#ifdef USE_VIDEO
rkVideoFaceOnOff(1);
#endif
}
static int stmDoFaceOff(void *data,MyVideo *arg)
{
#ifdef USE_VIDEO
printf("face off\n");
rkVideoFaceOnOff(0);
printf("face off end\n");
#endif
st_data = (StmData *)stm->initPara(stm,
sizeof(StmData));
if(data)
memcpy(st_data,data,sizeof(StmData));
stm->msgPost(stm,EV_FACE_OFF_FINISH,st_data);
}
static int stmDoFaceRegist(void *data,MyVideo *arg)
{
if (my_face)
return my_face->regist((MyFaceRegistData *)data);
else
return -1;
}
static int stmDoFaceRecognizer(void *data,MyVideo *arg)
{
if (my_face)
return my_face->recognizerOnce((MyFaceRecognizer *)data);
else
return -1;
}
#ifdef USE_VIDEO
static void sendVideoCallbackFunc(void *data,int size,int fram_type)
{
protocol_talk->sendVideo(data,size);
}
#else
static void* sendVideoCallbackFunc(void *arg)
{
send_video_start = 1;
if (share_mem == NULL)
share_mem = shareMemoryCreateSlave(1024*50,4);
if (share_mem == NULL) {
printf("[%s]main:share mem create fail\n",__func__);
return NULL;
}
while (send_video_start) {
int mem_len = 0;
char *mem_data = (char *)share_mem->GetStart(share_mem,&mem_len);
if (!mem_data || mem_len == 0) {
share_mem->GetEnd(share_mem);
goto send_sleep;
}
protocol_talk->sendVideo(mem_data,mem_len);
share_mem->GetEnd(share_mem);
send_sleep:
usleep(10000);
}
share_mem->CloseMemory(share_mem);
share_mem->Destroy(share_mem);
share_mem = NULL;
return NULL;
}
#endif
static void dialCallBack(int result)
{
if (result) {
talk_peer_dev.call_out_result = CALL_RESULT_SUCCESS;
stm->msgPost(stm,EV_TALK_CALLOUTOK,NULL);
if ( talk_peer_dev.type != DEV_TYPE_ENTRANCEMACHINE
&& talk_peer_dev.type != DEV_TYPE_HOUSEENTRANCEMACHINE) {
#ifdef USE_VIDEO
rkH264EncOn(320,240,sendVideoCallbackFunc);
#endif
}
} else {
talk_peer_dev.call_out_result = CALL_RESULT_FAIL;
st_data = (StmData *)stm->initPara(stm,
sizeof(StmData));
st_data->hangup_type = HANGUP_TYPE_PEER;
printf("[%s,%d]%d\n", __func__,__LINE__,st_data->hangup_type);
stm->msgPost(stm,EV_TALK_HANGUP,st_data);
}
}
static int stmDoTalkCallout(void *data,MyVideo *arg)
{
StmData *data_temp = (StmData *)data;
char ui_title[128] = {0};
int ret = sqlGetUserInfoUseUserId(data_temp->usr_id,data_temp->nick_name,&data_temp->type);
if (ret == 0) {
printf("can't find usr_id:%s\n", data_temp->usr_id);
st_data = (StmData *)stm->initPara(stm,
sizeof(StmData));
st_data->hangup_type = HANGUP_TYPE_BUTTON;
printf("[%s,%d]%d\n", __func__,__LINE__,st_data->hangup_type);
stm->msgPost(stm,EV_TALK_HANGUP,st_data);
return -1;
}
sprintf(ui_title,"正在呼叫 %s",data_temp->nick_name);
strcpy(talk_peer_dev.peer_nick_name,data_temp->nick_name);
talk_data.call_dir = CALL_DIR_OUT;
if (protocol_talk->uiShowFormVideo)
protocol_talk->uiShowFormVideo(data_temp->type,ui_title,talk_data.call_dir);
talk_peer_dev.type = data_temp->type;
talk_peer_dev.call_time = TIME_CALLING;
protocol_talk->dial(data_temp->usr_id,dialCallBack);
if (talk_peer_dev.type == DEV_TYPE_ENTRANCEMACHINE
|| talk_peer_dev.type == DEV_TYPE_HOUSEENTRANCEMACHINE) {
my_video->showPeerVideo();
gpioTalkDirIn();
} else {
gpioTalkDirOut();
}
// 保存通话记录到内存
strcpy(talk_data.nick_name,data_temp->nick_name);
getDate(talk_data.date,sizeof(talk_data.date));
}
static void *threadCallOutAll(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
char user_id[128] = {0};
int index = 0;
int talk_online_times = 10 * 10; // 判断云对讲是否连上服务,超过10S未连上服务,则不呼叫
int user_num = sqlGetUserInfoUseScopeStart(DEV_TYPE_HOUSEHOLDAPP);
sqlGetUserInfoEnd();
protocol_talk->type = PROTOCOL_TALK_CLOUD;
while (user_num) {
#ifdef USE_UCPAAS
if (ucsConnectState() == 0) {
if (talk_online_times) {
if (--talk_online_times == 0) {
user_num = 0;
break;
}
}
usleep(100000);
continue;
}
#endif
sqlGetUserInfosUseScopeIndex(user_id,DEV_TYPE_HOUSEHOLDAPP,index++);
#ifdef USE_UCPAAS
ucsHangup();
#endif
my_video->videoCallOut(user_id);
printf("[%s]id:%s,name:%s\n", __func__,user_id,talk_peer_dev.peer_nick_name);
int wait_times = 3000;
while (wait_times) {
if (talk_peer_dev.call_out_result == CALL_RESULT_NO) {
usleep(10000);
wait_times--;
continue;
}
if (talk_peer_dev.call_out_result == CALL_RESULT_SUCCESS) {
talk_peer_dev.call_out_result = CALL_RESULT_NO;
return NULL;
}
if (talk_peer_dev.call_out_result == CALL_RESULT_FAIL) {
talk_peer_dev.call_out_result = CALL_RESULT_NO;
break;
}
}
user_num--;
}
if (user_num == 0) {
st_data = (StmData *)stm->initPara(stm,
sizeof(StmData));
st_data->hangup_type = HANGUP_TYPE_BUTTON;
stm->msgPost(stm,EV_TALK_HANGUPALL,st_data);
}
return NULL;
}
static int stmDoTalkCalloutAll(void *data,MyVideo *arg)
{
createThread(threadCallOutAll,NULL);
}
static int stmDoTalkCallin(void *data,MyVideo *arg)
{
char ui_title[128] = {0};
StmData *data_temp = (StmData *)data;
int ret = sqlGetUserInfoUseUserId(data_temp->usr_id,data_temp->nick_name,&data_temp->type);
if (ret == 0) {
strcpy(data_temp->nick_name,data_temp->usr_id);
data_temp->type = DEV_TYPE_UNDEFINED;
printf("can't find usr_id:%s\n", data_temp->usr_id);
}
strcpy(talk_peer_dev.peer_nick_name,data_temp->nick_name);
sprintf(ui_title,"%s 正在呼叫",talk_peer_dev.peer_nick_name);
// 3000局域网对讲默认为门口机
if (protocol_talk->type == PROTOCOL_TALK_LAN) {
data_temp->type = DEV_TYPE_ENTRANCEMACHINE;
}
talk_data.call_dir = CALL_DIR_IN;
if (protocol_talk->uiShowFormVideo)
protocol_talk->uiShowFormVideo(data_temp->type,ui_title,talk_data.call_dir);
// 保存通话记录到内存
strcpy(talk_data.nick_name,data_temp->nick_name);
getDate(talk_data.date,sizeof(talk_data.date));
talk_peer_dev.type = data_temp->type;
talk_peer_dev.call_time = TIME_CALLING;
if (data_temp->type == DEV_TYPE_HOUSEHOLDAPP) {
my_video->videoAnswer(CALL_DIR_OUT,data_temp->type);
gpioTalkDirOut();
} else {
gpioTalkDirIn();
myAudioPlayRing();
my_video->showPeerVideo();
}
return 0;
}
static int stmDoTalkAnswer(void *data,MyVideo *arg)
{
char ui_title[128] = {0};
if ( talk_peer_dev.type != DEV_TYPE_ENTRANCEMACHINE
&& talk_peer_dev.type != DEV_TYPE_HOUSEENTRANCEMACHINE) {
#ifdef USE_VIDEO
rkH264EncOn(320,240,sendVideoCallbackFunc);
#endif
}
memset(ui_title,0,sizeof(ui_title));
StmData *data_temp = (StmData *)data;
sprintf(ui_title,"正在与 %s 通话",talk_peer_dev.peer_nick_name);
if (talk_peer_dev.type == DEV_TYPE_HOUSEHOLDAPP) {
formVideoLayerScreenOff();
}
protocol_talk->answer();
if (protocol_talk->uiAnswer)
protocol_talk->uiAnswer(ui_title);
talk_peer_dev.call_time = TIME_TALKING;
talk_data.answered = 1;
}
static int stmDoTalkHangupAll(void *data,MyVideo *arg)
{
printf("[%s,%d]\n", __func__,__LINE__);
protocol_talk->hangup(0);
}
static int stmDoTalkHangup(void *data,MyVideo *arg)
{
#ifdef USE_VIDEO
rkH264EncOff();
#endif
StmData *data_temp = (StmData *)data;
if (data_temp->hangup_type == HANGUP_TYPE_OVERTIME_UNANSWER) {
printf("[%s,%d]\n", __func__,__LINE__);
protocol_talk->hangup(1);
} else {
printf("[%s,%d]\n", __func__,__LINE__);
protocol_talk->hangup(0);
}
if (protocol_talk->uiHangup)
protocol_talk->uiHangup();
if (talk_data.answered) {
talk_data.talk_time = TIME_TALKING - talk_peer_dev.call_time;
} else {
talk_data.talk_time = TIME_CALLING - talk_peer_dev.call_time;
}
sqlInsertRecordTalkNoBack(talk_data.date,
talk_data.nick_name,
talk_data.call_dir,
talk_data.answered,
talk_data.talk_time,
talk_data.picture_id);
protocol_hardcloud->uploadPic(FAST_PIC_PATH,talk_data.picture_id);
protocol_hardcloud->reportTalk(&talk_data);
memset(&talk_data,0,sizeof(talk_data));
memset(&talk_peer_dev,0,sizeof(talk_peer_dev));
record_time = 0;
}
static void* threadCapture(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
CapData cap_data_temp;
memcpy(&cap_data_temp,arg,sizeof(CapData));
int i;
char jpg_name[64] = {0};
char file_path[64] = {0};
char url[256] = {0};
// printf("thread count:%d,date:%s,name:%s\n",cap_data_temp.count,cap_data_temp.file_date,cap_data_temp.file_name);
for (i=0; i<cap_data_temp.count; i++) {
sprintf(jpg_name,"%s_%s_%d.jpg",g_config.imei,cap_data_temp.file_name,i);
sprintf(file_path,"%s%s",FAST_PIC_PATH,jpg_name);
// printf("wirte :%s\n",file_path);
#ifdef USE_VIDEO
rkVideoCapture(file_path);
#ifdef X86
FILE *fp = fopen(file_path,"wb");
if (fp)
fclose(fp);
#endif
#endif
sprintf(url,"%s/%s",QINIU_URL,jpg_name);
sqlInsertPicUrlNoBack(cap_data_temp.pic_id,url);
usleep(500000);
}
sleep(1);
protocol_hardcloud->uploadPic(FAST_PIC_PATH,cap_data_temp.pic_id);
protocol_hardcloud->reportCapture(cap_data_temp.pic_id);
return NULL;
}
static void* threadCaptureOnce(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
CapData cap_data_temp;
memcpy(&cap_data_temp,arg,sizeof(CapData));
char jpg_name[64] = {0};
char file_path[64] = {0};
char url[256] = {0};
sprintf(jpg_name,"%s_%s_%d.jpg",g_config.imei,cap_data_temp.file_name,cap_data_temp.count - 1);
sprintf(file_path,"%s%s",FAST_PIC_PATH,jpg_name);
#ifdef USE_VIDEO
rkVideoCapture(file_path);
#ifdef X86
FILE *fp = fopen(file_path,"wb");
if (fp)
fclose(fp);
#endif
#endif
sprintf(url,"%s/%s",QINIU_URL,jpg_name);
sqlInsertPicUrlNoBack(cap_data_temp.pic_id,url);
sleep(2);
return NULL;
}
static void* threadAlarm(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
CapData cap_data_temp;
memcpy(&cap_data_temp,arg,sizeof(CapData));
int i;
char jpg_name[64] = {0};
char file_path[64] = {0};
char url[256] = {0};
static ReportAlarmData alarm_data;
alarm_data.type = ALARM_TYPE_PEOPLES;
alarm_data.picture_id = cap_data_temp.pic_id;
alarm_data.has_people = 0;
FILE *fp = NULL;
for (i=0; i<cap_data_temp.count; i++) {
sprintf(jpg_name,"%s_%s_%d.jpg",g_config.imei,cap_data_temp.file_name,i);
sprintf(file_path,"%s%s",FAST_PIC_PATH,jpg_name);
#ifdef USE_VIDEO
rkVideoCapture(file_path);
#endif
// wait for write file
usleep(500000);
char pic_buf_jpg[100 * 1024] = {0};
unsigned char *pic_buf_yuv = NULL;
int yuv_len = 0;
int w = 0,h = 0;
int leng = 0;
fp = fopen(file_path,"rb");
if (fp) {
leng = fread(pic_buf_jpg,1,sizeof(pic_buf_jpg),fp);
fclose(fp);
jpegToYuv420sp((unsigned char *)pic_buf_jpg, leng,&w,&h, &pic_buf_yuv, &yuv_len);
if (my_video->faceRecognizer(pic_buf_yuv,w,h,&alarm_data.age,&alarm_data.sex) == 0)
alarm_data.has_people = 1;
sprintf(url,"%s/%s",QINIU_URL,jpg_name);
sqlInsertPicUrlNoBack(cap_data_temp.pic_id,url);
}
if (pic_buf_yuv)
free(pic_buf_yuv);
}
sqlInsertRecordAlarm(alarm_data.date,
alarm_data.type,
alarm_data.has_people,
alarm_data.age,
alarm_data.sex,
alarm_data.picture_id);
sleep(1);
protocol_hardcloud->uploadPic(FAST_PIC_PATH,alarm_data.picture_id);
protocol_hardcloud->reportAlarm(&alarm_data);
if (g_config.pir_alarm)
myAudioPlayAlarm();
return NULL;
}
static void* threadFace(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
CapData cap_data_temp;
memcpy(&cap_data_temp,arg,sizeof(CapData));
int i;
char file_path[64] = {0};
char jpg_name[64] = {0};
char url[256] = {0};
static ReportFaceData face_data;
strcpy(face_data.date,cap_data_temp.file_date);
strcpy(face_data.nick_name,cap_data_temp.nick_name);
strcpy(face_data.user_id,cap_data_temp.usr_id);
face_data.picture_id = cap_data_temp.pic_id;
for (i=0; i<cap_data_temp.count; i++) {
sprintf(jpg_name,"%s_%s_%d.jpg",g_config.imei,cap_data_temp.file_name,i);
sprintf(file_path,"%s%s",FAST_PIC_PATH,jpg_name);
#ifdef USE_VIDEO
rkVideoCapture(file_path);
#endif
sprintf(url,"%s/%s",QINIU_URL,jpg_name);
sqlInsertPicUrlNoBack(cap_data_temp.pic_id,url);
// wait for write file
usleep(500000);
}
sqlInsertRecordFaceNoBack(face_data.date,
face_data.user_id,
face_data.nick_name,
face_data.picture_id);
sleep(1);
protocol_hardcloud->uploadPic(FAST_PIC_PATH,face_data.picture_id);
protocol_hardcloud->reportFace(&face_data);
return NULL;
}
static int stmDoCaptureNoUi(void *data,MyVideo *arg)
{
StmData *data_temp = (StmData *)data;
switch(data_temp->cap_type)
{
case CAP_TYPE_FORMMAIN :
case CAP_TYPE_DOORBELL :
memset(&cap_data,0,sizeof(CapData));
getFileName(cap_data.file_name,cap_data.file_date);
cap_data.pic_id = atoll(cap_data.file_name);
cap_data.count = data_temp->cap_count;
sqlInsertRecordCapNoBack(cap_data.file_date,cap_data.pic_id);
createThread(threadCapture,&cap_data);
break;
case CAP_TYPE_TALK :
if (talk_data.picture_id == 0) {
memset(&cap_data,0,sizeof(CapData));
getFileName(cap_data.file_name,cap_data.file_date);
talk_data.picture_id = cap_data.pic_id = atoll(cap_data.file_name);
}
cap_data.count++;
createThread(threadCaptureOnce,&cap_data);
break;
case CAP_TYPE_ALARM :
memset(&cap_data,0,sizeof(CapData));
getFileName(cap_data.file_name,cap_data.file_date);
cap_data.pic_id = atoll(cap_data.file_name);
cap_data.count = data_temp->cap_count;
createThread(threadAlarm,&cap_data);
break;
case CAP_TYPE_FACE :
memset(&cap_data,0,sizeof(CapData));
getFileName(cap_data.file_name,cap_data.file_date);
cap_data.pic_id = atoll(cap_data.file_name);
cap_data.count = data_temp->cap_count;
if (data_temp->nick_name)
strcpy(cap_data.nick_name,data_temp->nick_name);
if (data_temp->usr_id)
strcpy(cap_data.usr_id,data_temp->usr_id);
createThread(threadFace,&cap_data);
break;
default:
break;
}
}
static int stmDoCapture(void *data,MyVideo *arg)
{
StmData *data_temp = (StmData *)data;
stmDoCaptureNoUi(data_temp,arg);
formCreateCaputure(data_temp->cap_count);
}
static void recordVideoCallbackFunc(void *data,int size,int fram_type)
{
if (avi == NULL)
return ;
// 从关键帧开始写视频
if (avi->FirstFrame) {
if (fram_type == 1) {
avi->FirstFrame = 0;
avi->WriteVideo(avi,data,size);
}
} else {
avi->WriteVideo(avi,data,size);
}
}
static void recordStopCallbackFunc(void)
{
printf("[%s]\n", __func__);
pthread_mutex_lock(&mutex);
if (avi)
avi->DestoryMPEG4(&avi);
pthread_mutex_unlock(&mutex);
record_state = 0;
protocol_hardcloud->uploadPic(FAST_PIC_PATH,cap_data.pic_id);
protocol_hardcloud->reportCapture(cap_data.pic_id);
}
static void recordStopCallbackFuncForTalk(void)
{
printf("[%s]\n", __func__);
pthread_mutex_lock(&mutex);
if (avi)
avi->DestoryMPEG4(&avi);
pthread_mutex_unlock(&mutex);
record_state = 0;
// protocol_hardcloud->uploadPic(FAST_PIC_PATH,cap_data.pic_id);
// protocol_hardcloud->reportCapture(cap_data.pic_id);
}
#if (defined X86)
static void* threadAviReadVideo(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
int i;
for (i=0; i<50; i++) {
char buf[100];
sprintf(buf,"%02d",i);
if (i == 0)
recordVideoCallbackFunc(buf,2,1);
else
recordVideoCallbackFunc(buf,2,0);
usleep(100000);
}
recordStopCallbackFunc();
stm->msgPost(stm,EV_RECORD_STOP_FINISHED,NULL);
}
#endif
static void* threadAviReadAudio(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
int audio_fp = -1;
avi->InitAudio(avi,2,8000,1024);
if (my_mixer) {
my_mixer->SetVolumeEx(my_mixer,g_config.talk_volume);
my_mixer->InitPlayAndRec(my_mixer,&audio_fp,8000,2);
}
while (avi) {
int real_size = 0;
char audio_buff[1024] = {0};
if (my_mixer)
real_size = my_mixer->Read(my_mixer,audio_buff,sizeof(audio_buff),2);
pthread_mutex_lock(&mutex);
if (avi)
avi->WriteAudio(avi,audio_buff,real_size);
pthread_mutex_unlock(&mutex);
usleep(10000);
}
if (my_mixer) {
if (audio_fp > 0)
my_mixer->DeInitPlay(my_mixer,&audio_fp);
}
return NULL;
}
static int stmDoRecordStart(void *data,MyVideo *arg)
{
int w = 0,h = 0;
char file_path[64] = {0};
char url[256] = {0};
char jpg_name[64] = {0};
if (record_state == 1)
return 0;
record_state = 1;
StmData *data_temp = (StmData *)data;
switch(data_temp->cap_type)
{
case CAP_TYPE_TALK :
{
w = 320; h = 240;
record_time = g_config.cap_talk.timer;
if (talk_data.picture_id == 0) {
memset(&cap_data,0,sizeof(CapData));
getFileName(cap_data.file_name,cap_data.file_date);
talk_data.picture_id = cap_data.pic_id = atoll(cap_data.file_name);
}
sprintf(jpg_name,"%s_%s_%d.mp4",g_config.imei,cap_data.file_name,cap_data.video_count++);
sprintf(file_path,"%s%s",FAST_PIC_PATH,jpg_name);
if (avi == NULL) {
avi = Mpeg4_Create(w,h,file_path,WRITE_READ);
avi->InitAudio(avi,2,8000,0);
}
#ifdef USE_VIDEO
rkVideoRecordStart(w,h,recordVideoCallbackFunc);
rkVideoRecordSetStopFunc(recordStopCallbackFuncForTalk);
#endif
sprintf(url,"%s/%s",QINIU_URL,jpg_name);
sqlInsertRecordUrlNoBack(cap_data.pic_id,url);
}
break;
case CAP_TYPE_FORMMAIN :
{
w = 640; h = 480;
record_time = g_config.record_time;
memset(&cap_data,0,sizeof(CapData));
gpioTalkDirOut();
getFileName(cap_data.file_name,cap_data.file_date);
cap_data.pic_id = atoll(cap_data.file_name);
sqlInsertRecordCapNoBack(cap_data.file_date,cap_data.pic_id);
sprintf(jpg_name,"%s_%s.mp4",g_config.imei,cap_data.file_name);
sprintf(file_path,"%s%s",FAST_PIC_PATH,jpg_name);
if (avi == NULL) {
avi = Mpeg4_Create(w,h,file_path,WRITE_READ);
createThread(threadAviReadAudio,NULL);
}
#ifdef USE_VIDEO
rkVideoRecordStart(w,h,recordVideoCallbackFunc);
rkVideoRecordSetStopFunc(recordStopCallbackFunc);
#endif
#ifdef X86
createThread(threadAviReadVideo,NULL);
#endif
sprintf(url,"%s/%s",QINIU_URL,jpg_name);
sqlInsertRecordUrlNoBack(cap_data.pic_id,url);
}
break;
case CAP_TYPE_ALARM :
{
printf("file_name\n");
}
break;
default:
break;
}
}
static int stmDoRecordStop(void *data,MyVideo *arg)
{
if (record_state == 0)
return 0;
record_state = 0;
#ifdef USE_VIDEO
rkVideoRecordStop();
// 若正在通话,则不关闭h264编码
if (stm->getCurrentstate(stm) == ST_RECORD_STOPPING) {
rkH264EncOff();
if (protocol_talk->uiHangup)
protocol_talk->uiHangup();
}
#endif
record_time = 0;
stm->msgPost(stm,EV_RECORD_STOP_FINISHED,NULL);
}
static int stmDoDelaySleepTime(void *data,MyVideo *arg)
{
StmData *data_temp = (StmData *)data;
if (data_temp->type) {
resetAutoSleepTimerLong();
} else {
resetAutoSleepTimerShort();
}
}
static int stmDoUpdate(void *data,MyVideo *arg)
{
StmData *data_temp = (StmData *)data;
myUpdateStart(data_temp->type,data_temp->ip,data_temp->port,data_temp->file_path);
}
static StmDo stm_do[] =
{
{DO_FAIL, stmDoFail},
{DO_NOTHING, stmDoNothing},
{DO_FACE_ON, stmDoFaceOn},
{DO_FACE_OFF, stmDoFaceOff},
{DO_FACE_REGIST, stmDoFaceRegist},
{DO_FACE_RECOGNIZER,stmDoFaceRecognizer},
{DO_TALK_CALLOUT, stmDoTalkCallout},
{DO_TALK_CALLOUTALL,stmDoTalkCalloutAll},
{DO_TALK_CALLIN, stmDoTalkCallin},
{DO_TALK_ANSWER, stmDoTalkAnswer},
{DO_TALK_HANGUP, stmDoTalkHangup},
{DO_TALK_HANGUPALL, stmDoTalkHangupAll},
{DO_CAPTURE, stmDoCapture},
{DO_CAPTURE_NO_UI, stmDoCaptureNoUi},
{DO_RECORD_START, stmDoRecordStart},
{DO_RECORD_STOP, stmDoRecordStop},
{DO_DELAY_SLEEP, stmDoDelaySleepTime},
{DO_UPDATE, stmDoUpdate},
};
static int stmHandle(StMachine *This,int result,void *data,void *arg)
{
if (result) {
return stm_do[This->getCurRun(This)].proc(data,(MyVideo *)arg);
} else {
return stm_do[DO_FAIL].proc(data,(MyVideo *)arg);
}
}
static void* threadVideoInit(void *arg)
{
while (access(IPC_CAMMER,0) == 0) {
usleep(10000);
}
#ifdef USE_VIDEO
rkVideoInit();
#endif
return NULL;
}
static void init(void)
{
jpegIncDecInit();
myFaceInit();
createThread(threadVideoInit,NULL);
}
static void capture(int type,int count,char *nick_name,char *user_id)
{
#ifdef USE_VIDEO
if (rkGetVideoRun() == 0) {
topMsgCammerError();
return;
}
#endif
st_data = (StmData *)stm->initPara(stm,
sizeof(StmData));
st_data->cap_count = count;
st_data->cap_type = type;
if (nick_name)
strcpy(st_data->nick_name,nick_name);
if (user_id)
strcpy(st_data->usr_id,user_id);
stm->msgPost(stm,EV_CAPTURE,st_data);
}
static int recordStart(int type)
{
#ifdef USE_VIDEO
if (rkGetVideoRun() == 0) {
topMsgCammerError();
return 0;
}
#endif
st_data = (StmData *)stm->initPara(stm,
sizeof(StmData));
st_data->cap_type = type;
stm->msgPost(stm,EV_RECORD_START,st_data);
return 1;
}
static void recordStop(void)
{
stm->msgPost(stm,EV_RECORD_STOP,NULL);
}
static void recordWriteCallback(char *data,int size)
{
if (!avi)
return;
if (avi->FirstFrame == 0)
avi->WriteAudio(avi,data,size);
}
static void videoCallOut(char *user_id)
{
// int scope = 0;
st_data = (StmData *)stm->initPara(stm,
sizeof(StmData));
strcpy(st_data->usr_id,user_id);
stm->msgPost(stm,EV_TALK_CALLOUT,st_data);
// sqlGetUserInfoUseUserId(user_id,talk_peer_dev.peer_nick_name,&scope);
talk_peer_dev.call_out_result = CALL_RESULT_NO;
}
static int videoGetCallTime(void)
{
return talk_peer_dev.call_time;
}
static int videoGetRecordTime(void)
{
return record_time;
}
static void videoCallOutAll(void)
{
stm->msgPost(stm,EV_TALK_CALLOUTALL,NULL);
}
static void videoCallIn(char *user_id)
{
st_data = (StmData *)stm->initPara(stm,
sizeof(StmData));
strcpy(st_data->usr_id,user_id);
stm->msgPost(stm,EV_TALK_CALLIN,st_data);
}
static void videoHangup(enum HangupType hangup_type)
{
printf("[%s,%d]%d\n", __func__,__LINE__,hangup_type);
st_data = (StmData *)stm->initPara(stm,
sizeof(StmData));
st_data->hangup_type = hangup_type;
stm->msgPost(stm,EV_TALK_HANGUP,st_data);
}
static void videoAnswer(int dir,int dev_type)
{
st_data = (StmData *)stm->initPara(stm,
sizeof(StmData));
st_data->call_dir = dir;
st_data->type = dev_type;
stm->msgPost(stm,EV_TALK_ANSWER,st_data);
}
static void* threadFaceOnDelay(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
sleep(4);
stm->msgPost(stm,EV_FACE_ON,NULL);
return NULL;
}
static void showLocalVideo(void)
{
#ifdef USE_VIDEO
rkVideoDisplayLocal();
#endif
createThread(threadFaceOnDelay,NULL);
// stm->msgPost(stm,EV_FACE_ON,NULL);
}
static void receiveVideo(void *data,int *size)
{
protocol_talk->receiveVideo(data,size);
}
static void showPeerVideo(void)
{
#ifdef USE_VIDEO
rkVideoDisplayPeer(1024,600,receiveVideo);
#endif
}
static void hideVideo(void)
{
#ifdef USE_VIDEO
rkVideoDisplayOff();
#endif
}
static int faceRegist( unsigned char *image_buff,int w,int h,char *id,char *nick_name,char *url)
{
MyFaceRegistData face_data;
face_data.image_buff = image_buff;
face_data.w = w;
face_data.h = h;
face_data.id = id;
face_data.nick_name = nick_name;
face_data.url = url;
return stm->msgPostSync(stm,EV_FACE_REGIST,&face_data);
}
static void faceDelete(char *id)
{
if (my_face)
my_face->deleteOne(id);
}
static int faceRecognizer( unsigned char *image_buff,int w,int h,int *age,int *sex)
{
MyFaceRecognizer face_data;
face_data.image_buff = image_buff;
face_data.w = w;
face_data.h = h;
int ret = stm->msgPostSync(stm,EV_FACE_RECOGNIZER,&face_data);
if (ret == 0) {
*age = face_data.age;
*sex = face_data.sex;
}
return ret;
}
static int delaySleepTime(int type) // 延长睡眠时间0短 1长
{
st_data = (StmData *)stm->initPara(stm,
sizeof(StmData));
st_data->type = type;
stm->msgPost(stm,EV_DELAY_SLEEP,st_data);
}
static int update(int type,char *ip,int port,char *file_path)
{
st_data = (StmData *)stm->initPara(stm,
sizeof(StmData));
st_data->type = type;
st_data->port = port;
strcpy(st_data->ip,ip);
strcpy(st_data->file_path,file_path);
stm->msgPost(stm,EV_UPDATE,st_data);
}
static int isVideoOn(void)
{
if (stm->getCurrentstate(stm) == ST_TALK_CALLOUT
|| stm->getCurrentstate(stm) == ST_TALK_CALLOUTALL
|| stm->getCurrentstate(stm) == ST_TALK_CALLIN
|| stm->getCurrentstate(stm) == ST_TALK_TALKING)
return 1;
else
return 0;
}
static int isTalking(void)
{
if (stm->getCurrentstate(stm) == ST_TALK_TALKING)
return 1;
else
return 0;
}
static void resetCallTime(int call_time)
{
talk_peer_dev.call_time = call_time;
}
static void* threadVideoTimer(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
while (1) {
if (talk_peer_dev.call_time) {
// printf("call time:%d\n", talk_peer_dev.call_time);
if (--talk_peer_dev.call_time == 0) {
st_data = (StmData *)stm->initPara(stm,
sizeof(StmData));
if (talk_data.answered)
st_data->hangup_type = HANGUP_TYPE_OVERTIME_ANSWER;
else
st_data->hangup_type = HANGUP_TYPE_OVERTIME_UNANSWER;
printf("[%s,%d]%d\n", __func__,__LINE__,st_data->hangup_type);
stm->msgPost(stm,EV_TALK_HANGUP,st_data);
}
}
if (avi && record_time) {
if (avi->FirstFrame == 0) {
if (--record_time == 0) {
stm->msgPost(stm,EV_RECORD_STOP,NULL);
}
}
}
sleep(1);
}
return NULL;
}
void myVideoInit(void)
{
my_video = (MyVideo *) calloc(1,sizeof(MyVideo));
my_video->showLocalVideo = showLocalVideo;
my_video->showPeerVideo = showPeerVideo;
my_video->hideVideo = hideVideo;
my_video->faceRegist = faceRegist;
my_video->faceDelete = faceDelete;
my_video->faceRecognizer = faceRecognizer;
my_video->capture = capture;
my_video->recordStart = recordStart;
my_video->recordStop = recordStop;
my_video->videoCallOut = videoCallOut;
my_video->videoCallOutAll = videoCallOutAll;
my_video->videoCallIn = videoCallIn;
my_video->videoHangup = videoHangup;
my_video->videoAnswer = videoAnswer;
my_video->videoGetCallTime = videoGetCallTime;
my_video->videoGetRecordTime = videoGetRecordTime;
my_video->recordWriteCallback = recordWriteCallback;
my_video->delaySleepTime = delaySleepTime;
my_video->update = update;
my_video->isVideoOn = isVideoOn;
my_video->isTalking = isTalking;
my_video->resetCallTime = resetCallTime;
memset(&talk_data,0,sizeof(talk_data));
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
init();
stm = stateMachineCreate(ST_IDLE,
state_table,
sizeof (state_table) / sizeof ((state_table) [0]),
0,
stmHandle,
my_video,
&st_debug);
createThread(threadVideoTimer,NULL);
}
<file_sep>/src/gui/my_controls/my_title.h
/*
* =============================================================================
*
* Filename: my_title.h
*
* Description: 自定义静态控件
*
* Version: 1.0
* Created: 2019-04-23 19:46:14
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_TITLE_H
#define _MY_TITLE_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include "my_controls.h"
#include "commongdi.h"
#define CTRL_MYTITLE ("mytitle")
enum {
MSG_MYTITLE_SET_TITLE = MSG_USER + 1,
MSG_MYTITLE_SET_SWICH,
};
enum { // 左边类型
MYTITLE_LEFT_EXIT, // 退出按键
MYTITLE_LEFT_NULL, // 空
};
enum { // 右边类型
MYTITLE_RIGHT_NULL, // 空
MYTITLE_RIGHT_TEXT, // 文字
MYTITLE_RIGHT_SWICH, // 图片-开关
MYTITLE_RIGHT_ADD, // 图片-添加
};
enum {
MYTITLE_SWICH_OFF = 0,
MYTITLE_SWICH_ON,
};
enum { // 按键类型
MYTITLE_BUTTON_NULL = 0,
MYTITLE_BUTTON_EXIT,
MYTITLE_BUTTON_TEXT,
MYTITLE_BUTTON_ADD,
MYTITLE_BUTTON_SWICH,
};
typedef struct {
RECT rc; // 按钮位置
int state; // 按钮状态
BITMAP *image_nor; //按下图片 无则为null
BITMAP *image_pre; //抬起图片
}MyTitleButton;
typedef struct {
char text[64]; // 中间文字
char text_right[64];// 右边文字
PLOGFONT font; // 字体
int font_color; // 文字颜色
int bkg_color; // 背景颜色
int flag_left; // 左边类型
int flag_right; // 右边类型
MyTitleButton bt_exit; //退出按钮
MyTitleButton bt_add; //添加按钮
MyTitleButton bt_swich; //开关按钮
int click_x,click_y; //点击坐标
}MyTitleCtrlInfo;
typedef struct _MyCtrlTitle{
HWND idc; // 控件ID
int flag_left; // 左边类型
int flag_right; // 右边类型
int16_t x,y,w,h;
const char *text; // 中间文字
const char *text_right; // 右边文字
int font_color, bkg_color; // 文字颜色 // 背景颜色
NOTIFPROC notif_proc; // 回调函数
PLOGFONT font; // 字体
}MyCtrlTitle;
HWND createMyTitle(HWND hWnd,MyCtrlTitle *);
MyControls *my_title;
void initMyTitle(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/wireless/my_http.h
/*
* =============================================================================
*
* Filename: my_http.h
*
* Description: 封装tcp/ip接口
*
* Version: 1.0
* Created: 2019-05-21 11:32:52
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_HTTP_H
#define _MY_HTTP_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include "my_update.h"
typedef struct _MyHttp {
int (*post)(char *url, char *para, char **out_data);
int (*download)(char *url, char *para, char *file_path,UpdateFunc callback);
int (*upload)(char *url, char *para, char **out_data);
int (*qiniuUpload)(char *url,
char *para,
char *token,
char *file_path,
char *file_name,
char **out_data);
}MyHttp;
MyHttp * myHttpCreate(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/state_machine.c
/* * =============================================================================
*
* Filename: StateMachine.c
*
* Description: 状态机
*
* Version: 1.0
* Created: 2016-03-09 11:22:34
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include "queue.h"
#include "debug.h"
#include "thread_helper.h"
#include "state_machine.h"
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_MACHINE > 0
#define DBG_P( ... ) DPRINT( __VA_ARGS__ )
#else
#define DBG_P(...)
#endif
#define MAX_MSG 5
#define TSK_BUSY 0x80
#define TSK_READY 0x01
typedef struct _MsgData {
int msg;
void *data;
}MsgData;
typedef struct _StMachinePriv {
Queue *queue;
pthread_mutex_t mutex;
StateTable *funcentry;
StateTableDebug *st_debug;
void *arg;
int cur_state;
int status_run;
int table_num;
}StMachinePriv;
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
static int stmExecEntry(StMachine *This,int msg);
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*/
/**
* @brief stmMsgPost 状态机发送事件消息
*
* @param This
* @param msg 消息
* @param data 附加参数
*/
/* ---------------------------------------------------------------------------*/
static void stmMsgPost(StMachine* This,int msg,void *data)
{
MsgData msg_data;
msg_data.msg = msg;
msg_data.data = data;
This->priv->queue->post(This->priv->queue,&msg_data);
}
static int stmMsgPostSync(StMachine* This,int msg,void *data)
{
int ret = -1;
pthread_mutex_lock(&This->priv->mutex);
if (stmExecEntry(This,msg)) {
printf("%s\n",__func__ );
ret = This->handle(This,1,data,This->priv->arg);
}
pthread_mutex_unlock(&This->priv->mutex);
return ret;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmExecEntry 状态机执行状态判断和转换
*
* @param This
* @param msg 消息
*
* @returns 1成功 0失败
*/
/* ---------------------------------------------------------------------------*/
static int stmExecEntry(StMachine *This,int msg)
{
int num = This->priv->table_num;
StateTable *funcentry = This->priv->funcentry;
for (; num > 0; num--,funcentry++) {
if ( (msg == funcentry->msg)
&& (This->priv->cur_state == funcentry->cur_state)) {
if (This->priv->st_debug) {
DBG_P("[ST->msg:%s,cur:%s,next:%s,do:%s]\n",
This->priv->st_debug->ev[msg],
This->priv->st_debug->st[funcentry->cur_state],
This->priv->st_debug->st[funcentry->next_state],
This->priv->st_debug->todo[funcentry->run]);
}
This->priv->status_run = funcentry->run ;
This->priv->cur_state = funcentry->next_state;
return 1;
}
}
return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmInitPara 初始化发送状态机消息时带的参数
*
* @param This
* @param size 参数大小
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static void *stmInitPara(StMachine *This,int size)
{
void *para = NULL;
if (size) {
para = (void *) calloc (1,size);
}
return para;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmGetCurrentState 获取状态机当前状态
*
* @param This
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int stmGetCurrentState(StMachine *This)
{
return This->priv->cur_state;
}
static int stmGetCurRun(StMachine *This)
{
return This->priv->status_run;
}
static void stmSetCurrentState(StMachine *This,int state)
{
This->priv->cur_state = state;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmDestroy 销毁状态机
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void stmDestroy(StMachine **This)
{
if ((*This)->priv)
free((*This)->priv);
if (*This)
free(*This);
*This = NULL;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmThread 状态机处理
*
* @param arg
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static void *stmThread(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
StMachine *stm= (StMachine *)arg;
MsgData msg_data;
while(1) {
memset(&msg_data,0,sizeof(MsgData));
stm->priv->queue->get(stm->priv->queue,&msg_data);
pthread_mutex_lock(&stm->priv->mutex);
if (stmExecEntry(stm,msg_data.msg))
stm->handle(stm,1,msg_data.data,stm->priv->arg);
else
stm->handle(stm,0,&msg_data.msg,stm->priv->arg);
if (msg_data.data)
free(msg_data.data);
pthread_mutex_unlock(&stm->priv->mutex);
}
pthread_exit(NULL);
return NULL;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stateMachineCreate 创建状态机
*
* @param init_state 初始状态
* @param state_table 状态机表
* @param num 状态机表的数量
* @param id 状态机的ID,区别多个状态机同时运行
* @param handle 状态机处理,
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
StMachine* stateMachineCreate(int init_state,
StateTable *state_table,
int num,
int id,
int (*handle)(StMachine *This,int result,void *data,void *arg),
void *arg,
StateTableDebug *st_debug)
{
StMachine *This = (StMachine *)calloc(1,sizeof(StMachine));
This->priv = (StMachinePriv *)calloc(1,sizeof(StMachinePriv));
This->priv->arg = arg;
This->priv->funcentry = (StateTable *)state_table;
This->priv->table_num = num;
This->priv->cur_state = init_state;
This->priv->queue = queueCreate("stm",QUEUE_BLOCK,sizeof(MsgData));
This->priv->st_debug = st_debug;
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&This->priv->mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
This->id = id;
This->msgPost = stmMsgPost;
This->msgPostSync = stmMsgPostSync;
This->handle = handle;
This->initPara = stmInitPara;
This->getCurrentstate = stmGetCurrentState;
This->setCurrentstate = stmSetCurrentState;
This->getCurRun = stmGetCurRun;
This->destroy = stmDestroy;
createThread(stmThread,This);
return This;
}
<file_sep>/src/app/rdface/video_ion_alloc.c
#include <assert.h>
#include <execinfo.h>
#include <fcntl.h>
#include <malloc.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include "ion/ion.h"
#include "rk_fb/rk_fb.h"
#define DPRINT(...) \
do { \
printf("\033[1;32m"); \
printf("[FACE->%s,%d]",__func__,__LINE__); \
printf(__VA_ARGS__); \
printf("\033[0m"); \
} while (0)
int video_ion_free(struct video_ion* video_ion);
static int video_ion_alloc_buf(struct video_ion* video_ion)
{
int ret = ion_alloc(video_ion->client, video_ion->size, 0,
ION_HEAP_TYPE_DMA_MASK, 0, &video_ion->handle);
if (ret < 0) {
video_ion_free(video_ion);
DPRINT("ion_alloc failed!\n");
return -1;
}
ret = ion_share(video_ion->client, video_ion->handle, &video_ion->fd);
if (ret < 0) {
video_ion_free(video_ion);
DPRINT("ion_share failed!\n");
return -1;
}
ion_get_phys(video_ion->client, video_ion->handle, &video_ion->phys);
video_ion->buffer = mmap(NULL, video_ion->size, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_LOCKED, video_ion->fd, 0);
if (!video_ion->buffer) {
video_ion_free(video_ion);
DPRINT("%s mmap failed!\n", __func__);
return -1;
}
// DPRINT("--- ion alloc, get fd: %d\n", video_ion->fd);
return 0;
}
int video_ion_alloc_rational(struct video_ion* video_ion,
int width,
int height,
int num,
int den)
{
if (video_ion->client >= 0) {
DPRINT("warning: video_ion client has been already opened\n");
return -1;
}
video_ion->client = ion_open();
if (video_ion->client < 0) {
DPRINT("%s:open /dev/ion failed!\n", __func__);
return -1;
}
video_ion->width = width;
video_ion->height = height;
video_ion->size = ((width + 15) & ~15) * ((height + 15) & ~15) * num / den;
// DPRINT("video_ion->size:%d \n",video_ion->size);
return video_ion_alloc_buf(video_ion);
}
int video_ion_alloc(struct video_ion* video_ion, int width, int height)
{
return video_ion_alloc_rational(video_ion, width, height, 3, 2);
}
int video_ion_free(struct video_ion* video_ion)
{
int ret = 0;
if (video_ion->buffer) {
munmap(video_ion->buffer, video_ion->size);
video_ion->buffer = NULL;
}
if (video_ion->fd >= 0) {
DPRINT("--- ion free, release fd: %d\n", video_ion->fd);
close(video_ion->fd);
video_ion->fd = -1;
}
if (video_ion->client >= 0) {
if (video_ion->handle) {
ret = ion_free(video_ion->client, video_ion->handle);
if (ret)
DPRINT("ion_free failed!\n");
video_ion->handle = 0;
}
ion_close(video_ion->client);
video_ion->client = -1;
}
memset(video_ion, 0, sizeof(struct video_ion));
video_ion->client = -1;
video_ion->fd = -1;
return ret;
}
void video_ion_buffer_black(struct video_ion* video_ion, int w, int h)
{
memset(video_ion->buffer, 16, w * h);
memset((char *)video_ion->buffer + w * h, 128, w * h / 2);
}
<file_sep>/src/drivers/mp4_muxer/mp4_muxer.h
/*
* =============================================================================
*
* Filename: MP4Muxer.h
*
* Description: MP4视频音频封装,利用ffmpeg库
*
* Version: 1.0
* Created: 2019-09-12 09:30:11
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MP4_MUXER_H
#define _MP4_MUXER_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
int mp4MuxerAudioInit(int channels, long sample, int bits);
int mp4MuxerInit(int width,int height,char *file_name);
int mp4MuxerAppendVideo(uint8_t* data, int size);
int mp4MuxerAppendAudio(uint8_t* data, int size);
int mp4MuxerStop(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/gui/commongdi.c
/*
* =============================================================================
*
* Filename: commongdi.c
*
* Description: 公共自定义画图函数
*
* Version: 1.0
* Created: 2019-05-07 22:03:18
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "commongdi.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
/* ----------------------------------------------------------------*/
/**
* @brief myFillBox 填充矩形区域颜色,包含透明色
*
* @param hdc
* @param rc 矩形区域
* @param color 颜色
*/
/* ----------------------------------------------------------------*/
void myFillBox(HDC hdc, RECT *rc, int color)
{
#define PRECTW(rc) ((rc)->right - (rc)->left)
#define PRECTH(rc) ((rc)->bottom - (rc)->top)
HDC mem_dc = CreateMemDC (PRECTW(rc), PRECTH(rc), 32,
MEMDC_FLAG_HWSURFACE | MEMDC_FLAG_SRCALPHA | MEMDC_FLAG_SRCCOLORKEY,
0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);
SetBrushColor (mem_dc, RGBA2Pixel (mem_dc,
(color & 0xff000000) >> 24,
(color & 0x00ff0000) >> 16,
(color & 0x0000ff00) >> 8,
(color & 0x000000ff)) );
FillBox (mem_dc, rc->left, rc->top, PRECTW(rc),PRECTH(rc));
BitBlt (mem_dc, rc->left, rc->top, PRECTW(rc), PRECTH(rc), hdc, 0, 0,0);
DeleteMemDC (mem_dc);
}
//---------------------------------------------------------------------------
//绘制一个白色的底图
//---------------------------------------------------------------------------
void drawWhiteFrame (HWND hWnd, HDC hdc, const RECT* pClipRect,int Left,int Top,int Width,int Height)
{
// BOOL fGetDC = FALSE;
// RECT rcTemp;
// RECT rcClient;
// GetClientRect(hWnd,&rcClient);
// if (hdc == 0) {
// hdc = GetClientDC (hWnd);
// fGetDC = TRUE;
// }
// if (pClipRect) {
// rcTemp = *pClipRect;
// ScreenToClient (hWnd, &rcTemp.left, &rcTemp.top);
// ScreenToClient (hWnd, &rcTemp.right, &rcTemp.bottom);
// IncludeClipRect(hdc,&rcTemp);
// }
// Draw3DControlFrame(hdc,Left,Top,Width,Height,COLOR_lightwhite,0);
// if (fGetDC)
// ReleaseDC (hdc);
}
//---------------------------------------------------------------------------
/* ---------------------------------------------------------------------------*/
/**
* @brief drawBackground 绘制背景
*
* @param hWnd
* @param hdc
* @param pClipRect
* @param Image
*/
/* ---------------------------------------------------------------------------*/
void drawBackground(HWND hWnd, HDC hdc, const RECT* pClipRect,BITMAP *Image,int color)
{
BOOL fGetDC = FALSE;
RECT rcTemp;
RECT rcClient;
GetClientRect(hWnd,&rcClient);
if (hdc == 0) {
hdc = GetSecondaryClientDC (hWnd);
fGetDC = TRUE;
}
// if (pClipRect) {
// rcTemp = *pClipRect;
// ScreenToClient (hWnd, &rcTemp.left, &rcTemp.top);
// ScreenToClient (hWnd, &rcTemp.right, &rcTemp.bottom);
// IncludeClipRect(hdc,&rcTemp);
// }
if (Image)
FillBoxWithBitmap(hdc,rcClient.left,rcClient.top,RECTW(rcClient),RECTH(rcClient),Image);
else {
SetBrushColor (hdc,color);
FillBox (hdc, rcClient.left,rcClient.top,RECTW(rcClient),RECTH(rcClient));
}
if (fGetDC)
ReleaseSecondaryDC (hWnd,hdc);
}
//----------------------------------------------------------------------------
void wndEraseBackground(HWND hWnd,HDC hdc, const RECT* pClipRect,BITMAP *pImage,int Left,int Top,int Width,int Height)
{
BOOL fGetDC = FALSE;
RECT rcTemp;
if (hdc == 0) {
hdc = GetClientDC (hWnd);
fGetDC = TRUE;
}
if (pClipRect) {
rcTemp = *pClipRect;
ScreenToClient (hWnd, &rcTemp.left, &rcTemp.top);
ScreenToClient (hWnd, &rcTemp.right, &rcTemp.bottom);
IncludeClipRect(hdc,&rcTemp);
}
FillBoxWithBitmap(hdc,Left,Top,Width,Height,pImage);
if (fGetDC)
ReleaseDC (hdc);
}
/* ----------------------------------------------------------------*/
/**
* @brief lineA2B 绘制直线
*
* @param hdc
* @param a 起点
* @param b 终点
* @param color 颜色
*/
/* ----------------------------------------------------------------*/
void lineA2B (HDC hdc, POINT* a, POINT* b, int color)
{
SetPenColor (hdc, color);
MoveTo (hdc, a->x, a->y);
LineTo (hdc, b->x, b->y);
}
/* ----------------------------------------------------------------*/
/**
* @brief drawRectangle 绘制矩形 左上点(x0,y0) 右下点(x1,y1)
*
* @param hdc
* @param x0
* @param y0
* @param x1
* @param y1
* @param color 颜色
*/
/* ----------------------------------------------------------------*/
void drawRectangle (HDC hdc, int x0, int y0, int x1, int y1, int color)
{
SetPenColor (hdc, color);
Rectangle(hdc,x0,y0,x1,y1);
}
/* ----------------------------------------------------------------*/
/**
* @brief drawTriangle
* 填充三角形
* @param hdc
* @param rc
* @param color
* @param type 尖头方向 0:up 1:down 2:right 3:left
*/
/* ----------------------------------------------------------------*/
void drawTriangle (HDC hdc, RECT rc, int color, int type)
{
SetPenColor (hdc, color);
POINT* pts = (POINT*)malloc(sizeof(POINT) * 3);
switch (type)
{
case 0:
{
pts->x = rc.left + RECTW(rc) / 2;
pts->y = rc.top;
(pts + 1)->x = rc.left;
(pts + 1)->y = rc.bottom;
(pts + 2)->x = rc.right;
(pts + 2)->y = rc.bottom;
} break;
case 1:
{
pts->x = rc.left + RECTW(rc) / 2;
pts->y = rc.bottom;
(pts + 1)->x = rc.left;
(pts + 1)->y = rc.top;
(pts + 2)->x = rc.right;
(pts + 2)->y = rc.top;
} break;
case 2:
{
pts->x = rc.right;
pts->y = rc.top + RECTH(rc) / 2;
(pts + 1)->x = rc.left;
(pts + 1)->y = rc.top;
(pts + 2)->x = rc.left;
(pts + 2)->y = rc.bottom;
} break;
case 3:
{
pts->x = rc.left;
pts->y = rc.top + RECTH(rc) / 2;
(pts + 1)->x = rc.right;
(pts + 1)->y = rc.top;
(pts + 2)->x = rc.right;
(pts + 2)->y = rc.bottom;
} break;
}
FillPolygon(hdc,pts,3);
free(pts);
}
//----------------------------------------------------------------------------
// 显示一帧视频,VideoBuf为decode的缓冲区
// 缓冲区格式为DC_WIDTHXDC_HEIGHTX16Bit的RGB像素集
//----------------------------------------------------------------------------
void drawFrame(HWND hWnd,char *VideoBuf)
{
// int y;
// int width, height, pitch; //绘制的宽度,高度和每行的字节数
// RECT rc = {0, 0, 352, 288}; //DC_WIDTHXDC_HEIGHT
// HDC hdc = GetDC(hWnd); //在主界面直接绘制
// int bpp = GetGDCapability (hdc, GDCAP_BPP);
// Uint8* frame_buffer = LockDC (hdc, &rc, &width, &height, &pitch); //帧缓冲区地址,锁定
// Uint8* row = frame_buffer; //行缓冲区地址
// // VideoBuf += DC_WIDTH*(DC_HEIGHT-1)*DC_PIXEL;
// for (y = 0; y < height; y++) {
// FastCopy (row, VideoBuf, width * bpp); //高速拷屏
// row += pitch; //下一行
// VideoBuf += 352*2; //decode缓冲区每行字节数为DC_HEIGHT*2=576Byte
// }
// UnlockDC (hdc);
// ReleaseDC(hdc);
}
typedef struct BITMAPFILEHEADER
{
unsigned short bfType;
unsigned long bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
unsigned long bfOffBits;
} __attribute__ ((packed)) BITMAPFILEHEADER;
typedef struct BITMAPINFOHEADER /* size: 40 */
{
unsigned long biSize;
unsigned long biWidth;
unsigned long biHeight;
unsigned short biPlanes;
unsigned short biBitCount;
unsigned long biCompression;
unsigned long biSizeImage;
unsigned long biXPelsPerMeter;
unsigned long biYPelsPerMeter;
unsigned long biClrUsed;
unsigned long biClrImportant;
} __attribute__ ((packed)) BITMAPINFOHEADER;
//---------------------------------------------------------------------------
void getPartFromBmp(const BITMAP *bmp,BITMAP *DstBitmap,int Left,int Top,int Width,int Height)
{
int i,j;
int DstLineCnt;
int LineCnt;
char *pBmpBuf;
BITMAPFILEHEADER *head;
BITMAPINFOHEADER *info;
char *Pix; //目标像素
char *pSrc; //源文件像素
//目标每行缓冲区大小
DstLineCnt = Width*3;
if(DstLineCnt%4)
DstLineCnt += 4-DstLineCnt%4;
//分配空间
pBmpBuf = (char*)malloc(sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+DstLineCnt*Height);
head = (BITMAPFILEHEADER *)pBmpBuf;
info = (BITMAPINFOHEADER *)&pBmpBuf[sizeof(BITMAPFILEHEADER)];
head->bfType = 0x4d42;
head->bfSize = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+DstLineCnt*Height;
head->bfOffBits = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);
head->bfReserved1 = 0;
head->bfReserved2 = 0;
info->biSize = sizeof(BITMAPINFOHEADER);
info->biWidth = Width;
info->biHeight = Height;
info->biPlanes = 1;
info->biBitCount = 24;
info->biCompression = 0;
info->biSizeImage = 0;
info->biXPelsPerMeter = 0;
info->biYPelsPerMeter = 0;
info->biClrUsed = 0;
info->biClrImportant = 0;
//一行数据多少
LineCnt = bmp->bmWidth*2;
if(LineCnt%4)
LineCnt += 4-LineCnt%4;
//首数据
pSrc = &((char*)bmp->bmBits)[Top*LineCnt+Left*3];
//最后一行
Pix = &pBmpBuf[sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)]+(Height-1)*DstLineCnt;
for(i=0;i<Height;i++) {
char *pRGB = Pix;
unsigned short *pRGB2 = (unsigned short *)pSrc;
for(j=0;j<Width;j++) {
Pixel2RGB(HDC_SCREEN,*pRGB2,&pRGB[2],&pRGB[1],&pRGB[0]);
pRGB+=3;
pRGB2++;
}
pSrc+=LineCnt;
Pix-=DstLineCnt;
}
LoadBitmapFromMem(HDC_SCREEN,DstBitmap,pBmpBuf,head->bfSize,"png");
free(pBmpBuf);
}
/* ----------------------------------------------------------------*/
/**
* @brief setTranslate 设置透明按钮
*
* @param bmWidth
* @param bmHeight
* @param FgLine
* @param BkLine
* @param MkLine
* @param FgPitch
* @param BkPitch
* @param MkPitch
*/
/* ----------------------------------------------------------------*/
static void setTranslate(DWORD bmWidth,DWORD bmHeight,char *FgLine,char *BkLine,char *MkLine,
int FgPitch,int BkPitch,int MkPitch)
{
DWORD i,j;
WORD *BkBits,*FgBits,*MkBits;
for(i = 0;i<bmHeight;i++) {
FgBits = (WORD*)FgLine;
BkBits = (WORD*)BkLine;
MkBits = (WORD*)MkLine;
for(j=0;j<bmWidth;j++) {
#if 0 //简单透明运算,速度快
*FgBits = ((*BkBits)&(~(*MkBits))) | ((*FgBits) & (*MkBits));
#else //支持透明度透明运算,速度较慢
unsigned int dwTmp,A;
A = (*MkBits>>5) & 0x3F;
// R = (Bk * (64-A) + Fg * A) / 64;
dwTmp = ((*BkBits & 0x1F)*(64-A) + (*FgBits & 0x1F)*A)>>6; //R
// R = ((Bk * (64-A) + Fg * A) / 64) << 5;
dwTmp |= ((((*BkBits>>5) & 0x3F)*(64-A) + ((*FgBits>>5) & 0x3F)*A)>>1) & 0x7E0; //G
dwTmp |= ((((*BkBits>>11) & 0x1F)*(64-A) + ((*FgBits>>11) & 0x1F)*A)<<5) & 0xF800; //B
*BkBits = dwTmp;
#endif
FgBits++;
BkBits++;
MkBits++;
}
FgLine += FgPitch;
BkLine += BkPitch;
MkLine += MkPitch;
}
}
/* ----------------------------------------------------------------*/
/**
* @brief translateIconPart 绘制透明图标
*
* @param hdc
* @param x
* @param y
* @param w
* @param h
* @param FgBmp
* @param LineIconCnt
* @param IconIdx 绘制行中第几元素
* @param t
* @param Translate
*/
/* ----------------------------------------------------------------*/
void translateIconPart(HDC hdc,int x,int y,int w,int h,BITMAP *FgBmp,int LineIconCnt,int IconIdx,int t,
BOOL Translate)
{
if((LineIconCnt==4 || LineIconCnt==8) && Translate) {
BITMAP BkBmp;
char *BkLine,*FgLine,*MkLine;
memset(&BkBmp,0,sizeof(BITMAP));
GetBitmapFromDC(hdc,x,y,w,h,&BkBmp);
FgLine = FgBmp->bmBits+t*FgBmp->bmPitch+w*IconIdx*2;
BkLine = BkBmp.bmBits;
if(LineIconCnt==4) {
MkLine = FgLine+w*2*2;
} else {
MkLine = FgLine+w*4*2;
}
// setTranslate(w,h,FgLine,BkLine,MkLine,FgBmp->bmPitch,
// BkBmp.bmPitch,FgBmp->bmPitch);
FillBoxWithBitmap(hdc,x,y,w,h,&BkBmp);
UnloadBitmap(&BkBmp);
} else {
if(LineIconCnt>IconIdx) {
FillBoxWithBitmapPart (hdc, x, y, w, h, 0, 0, FgBmp,w*IconIdx, t);
} else {
FillBoxWithBitmapPart (hdc, x, y, w, h, 0, 0, FgBmp,w*(LineIconCnt-1), t);
}
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief bmpsLoad 装载图片资源
*
* @param bmp 图片结构
*/
/* ---------------------------------------------------------------------------*/
void bmpLoad(BITMAP *bmp,char *path)
{
char path_src[256];
// char path_back[256];
sprintf(path_src,"%s%s",BMP_RES_PATH,path);
// sprintf(path_back,"%s%s",BMP_RESBACK_PATH,path);
// printf("load back:%s\n",path_back );
if (LoadBitmap (HDC_SCREEN,bmp, path_src)) {
printf ("LoadBitmap(%s)fail.\n",path_src);
// excuteCmd(1,"cp",path_back,path_src,NULL);
// sync();
// if (LoadBitmap (HDC_SCREEN,bmp, path_src))
// printf ("LoadBitmaps(%s)fail-again!!.\n",path);
} else {
// printf ("LoadBitmap(%s)ok.\n",path_src);
}
}
void bmpsLoad(BmpLocation *bmp)
{
int i;
for (i=0; bmp->bmp != NULL; i++) {
bmpLoad(bmp->bmp,bmp->location);
bmp++;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief bmpsRelease 释放图片资源
*
* @param bmp 图片结构
* @param num 图片数目
*/
/* ---------------------------------------------------------------------------*/
void bmpRelease(BITMAP *bmp)
{
UnloadBitmap(bmp);
}
void bmpsRelease(BmpLocation *bmp)
{
int i;
for (i=0; bmp->bmp != NULL; i++) {
bmpRelease(bmp[i].bmp);
}
}
void fontsLoad(FontLocation *font)
{
int i;
for (i=0; font[i].font != NULL; i++) {
*font[i].font = CreateLogFont("ttf",
"song", "UTF-8",
font[i].first_type,
FONT_SLANT_ROMAN,
FONT_OTHER_NIL,
FONT_OTHER_LCDPORTRAIT,
FONT_UNDERLINE_NONE,
FONT_STRUCKOUT_NONE,
font[i].size, 0);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myMoveWindow 自定义窗口移动函数,保持原有窗口大小
*
* @param ctrl 控件ID
* @param x 新坐标
* @param y
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
int myMoveWindow(HWND ctrl, int x,int y)
{
RECT rc;
if (GetWindowRect (ctrl, &rc)) {
MoveWindow(ctrl, x,y,RECTW(rc),RECTH(rc),TRUE);
return TRUE;
} else
return FALSE;
}
<file_sep>/src/hal/gpio-rv1108.h
//--------------------------------------------------------------
//
// Copyright (c) Nuvoton Technology Corp. All rights reserved.
//
//--------------------------------------------------------------
#ifndef _RV1108GPIO_H__
#define _RV1108GPIO_H__
#include <linux/ioctl.h>
#include <linux/types.h>
#ifdef __cplusplus
extern "C"
{
#endif
// TO BE CONTINUED
//typedef struct {
// int32_t *inbuf;
// int32_t *outbuf;
// int32_t i32Size;
//} aac_enc_ctx_s;
// For AAC encoder, pass the parameters
// TO BE CONTINUED
//typedef struct {
// int32_t i32Size;
// int32_t *inbuf;
// int32_t *outbuf;
//} aac_dec_ctx_s;
// For AAC decoder, pass the parameters
#define GPIO_IOC_MAGIC 'h'
#define GPIO_IOC_MAXNR 100
/* ===========================================================
S means "Set" through a ptr
T means Tell" directly with the argument value
G means "Get": reply by setting through a pointer
Q means "Query": response is on the return value
X means "eXchange": switch G and S atomically
H means "sHift": switch T and Q atomically
============================================================ */
#define RV1108_IOCINIT _IOW(GPIO_IOC_MAGIC, 1, unsigned int)
#define RV1108_IOCREAD _IOR(GPIO_IOC_MAGIC, 2, unsigned int)
#define RV1108_IOCGPIO_CTRL _IOW(GPIO_IOC_MAGIC, 3, unsigned int)
#define RV1108_IOCGPIO_GET _IOR(GPIO_IOC_MAGIC, 4, unsigned int)
//#define RV1108_IOC_WATCHDOG _IOR(GPIO_IOC_MAGIC, 5, unsigned int)
//#define RV1108_IOC_RD_IMEI _IOR(GPIO_IOC_MAGIC, 6, unsigned int)
//#define RV1108_IOC_WR_IMEI _IOW(GPIO_IOC_MAGIC, 7, unsigned int)
//#define RV1108_IOC_NET_STATUS _IOR(GPIO_IOC_MAGIC, 8, unsigned int)
#ifdef __cplusplus
}
#endif
#endif
<file_sep>/src/app/video/h264_enc_dec/mpi_dec_api.c
/*
* Copyright 2015 Rockchip Electronics Co. LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <mpp/rk_mpi.h>
#include <mpp/mpp_log.h>
#include <mpi/mpp_mem.h>
#include <mpi/mpp_env.h>
#include <mpi/mpp_time.h>
#include <mpi/mpp_common.h>
#include "utils.h"
#include "mpi_dec_api.h"
#define MPI_DEC_STREAM_SIZE 1024*50
#define MAX_FILE_NAME_LENGTH 256
int split_h264_separate(const uint8_t *buffer, size_t length,int *sps_length,int *pps_length) ;
typedef struct {
MppApi *mpi;
/* end of stream flag when set quit the loop */
RK_U32 eos;
/* buffer for stream data reading */
char *buf;
/* input and output */
MppBufferGroup frm_grp;
MppPacket packet;
MppFrame frame;
RK_S32 frame_count;
size_t max_usage;
} MpiDecLoopData;
typedef struct {
MppCodingType type;
RK_U32 width;
RK_U32 height;
RK_U32 debug;
RK_S32 timeout;
size_t pkt_size;
// report information
size_t max_usage;
} MpiDecTestCmd;
H264Decode *my_h264dec;
static MpiDecTestCmd cmd_ctx;
// base flow context
static MppCtx ctx = NULL;
static MppApi *mpi = NULL;
// input / output
static MppPacket packet = NULL;
static MppFrame frame = NULL;
static char *buf = NULL;
static MpiDecLoopData data;
static char h264_sps_pps[64];
static int dump_mpp_frame_to_buf(MppFrame frame, unsigned char *out_data)
{
RK_U32 width = 0;
RK_U32 height = 0;
RK_U32 h_stride = 0;
RK_U32 v_stride = 0;
MppFrameFormat fmt = MPP_FMT_YUV420SP;
MppBuffer buffer = NULL;
RK_U8 *base = NULL;
if (NULL == frame)
return 0;
width = mpp_frame_get_width(frame);
height = mpp_frame_get_height(frame);
h_stride = mpp_frame_get_hor_stride(frame);
v_stride = mpp_frame_get_ver_stride(frame);
fmt = mpp_frame_get_fmt(frame);
buffer = mpp_frame_get_buffer(frame);
if (NULL == buffer)
return 0;
base = (RK_U8 *)mpp_buffer_get_ptr(buffer);
switch (fmt) {
case MPP_FMT_YUV422SP :
{
/* YUV422SP -> YUV422P for better display */
RK_U32 i, j;
RK_U8 *base_y = base;
RK_U8 *base_c = base + h_stride * v_stride;
RK_U8 *tmp = mpp_malloc(RK_U8, h_stride * height * 2);
RK_U8 *tmp_u = tmp;
RK_U8 *tmp_v = tmp + width * height / 2;
int index = 0;
for (i = 0; i < height; i++, base_y += h_stride) {
memcpy(&out_data[index],base_y,width);
index += width;
// fwrite(base_y, 1, width, fp);
}
for (i = 0; i < height; i++, base_c += h_stride) {
for (j = 0; j < width / 2; j++) {
tmp_u[j] = base_c[2 * j + 0];
tmp_v[j] = base_c[2 * j + 1];
}
tmp_u += width / 2;
tmp_v += width / 2;
}
memcpy(&out_data[index],tmp,width * height);
index += width * height;
mpp_free(tmp);
return index;
} break;
case MPP_FMT_YUV420SP :
{
int index = 0;
RK_U32 i;
RK_U8 *base_y = base;
RK_U8 *base_c = base + h_stride * v_stride;
for (i = 0; i < height; i++, base_y += h_stride) {
// fwrite(base_y, 1, width, fp);
memcpy(&out_data[index],base_y,width);
index += width;
}
for (i = 0; i < height / 2; i++, base_c += h_stride) {
// fwrite(base_c, 1, width, fp);
memcpy(&out_data[index],base_c,width);
index += width;
}
return index;
} break;
case MPP_FMT_YUV444SP :
{
/* YUV444SP -> YUV444P for better display */
int index = 0;
RK_U32 i, j;
RK_U8 *base_y = base;
RK_U8 *base_c = base + h_stride * v_stride;
RK_U8 *tmp = mpp_malloc(RK_U8, h_stride * height * 2);
RK_U8 *tmp_u = tmp;
RK_U8 *tmp_v = tmp + width * height;
for (i = 0; i < height; i++, base_y += h_stride) {
memcpy(&out_data[index],base_y,width);
index += width;
}
for (i = 0; i < height; i++, base_c += h_stride * 2) {
for (j = 0; j < width; j++) {
tmp_u[j] = base_c[2 * j + 0];
tmp_v[j] = base_c[2 * j + 1];
}
tmp_u += width;
tmp_v += width;
}
memcpy(&out_data[index],tmp,width * height*2);
// fwrite(tmp, 1, width * height * 2, fp);
mpp_free(tmp);
index += width * height;
return index;
} break;
default :
{
mpp_err("not supported format %d\n", fmt);
} break;
}
}
static int decode_simple(MpiDecLoopData *data,unsigned char *in_data,size_t read_size,unsigned char *out_data,int *out_w,int *out_h)
{
RK_U32 pkt_done = 0;
RK_U32 err_info = 0;
MPP_RET ret = MPP_OK;
RK_U32 buf_size = 0 ;
int out_size = 0;
// write data to packet
mpp_packet_write(packet, 0, in_data, read_size);
// reset pos and set valid length
// mpp_packet_set_pos(packet, in_data);
mpp_packet_set_length(packet, read_size);
do {
RK_S32 times = 5;
// send the packet first if packet is not done
if (!pkt_done) {
ret = mpi->decode_put_packet(ctx, packet);
if (MPP_OK == ret)
pkt_done = 1;
}
// then get all available frame and release
do {
RK_S32 get_frm = 0;
RK_U32 frm_eos = 0;
try_again:
ret = mpi->decode_get_frame(ctx, &frame);
if (MPP_ERR_TIMEOUT == ret) {
if (times > 0) {
times--;
msleep(2);
goto try_again;
}
printf("decode_get_frame failed too much time\n");
}
if (MPP_OK != ret) {
printf("decode_get_frame failed ret %d\n", ret);
break;
}
if (frame) {
if (mpp_frame_get_info_change(frame)) {
*out_w = mpp_frame_get_width(frame);
*out_h = mpp_frame_get_height(frame);
RK_U32 hor_stride = mpp_frame_get_hor_stride(frame);
RK_U32 ver_stride = mpp_frame_get_ver_stride(frame);
MppFrameFormat fmt = mpp_frame_get_fmt(frame);
buf_size = mpp_frame_get_buf_size(frame);
printf("decoder require buffer w:h [%d:%d] stride [%d:%d] buf_size %d[%d]\n",
*out_w, *out_h, hor_stride, ver_stride, buf_size,fmt);
if (NULL == data->frm_grp) {
/* If buffer group is not set create one and limit it */
ret = mpp_buffer_group_get_internal(&data->frm_grp, MPP_BUFFER_TYPE_ION);
if (ret) {
printf("get mpp buffer group failed ret %d\n", ret);
break;
}
/* Set buffer to mpp decoder */
ret = mpi->control(ctx, MPP_DEC_SET_EXT_BUF_GROUP, data->frm_grp);
if (ret) {
printf("set buffer group failed ret %d\n", ret);
break;
}
} else {
/* If old buffer group exist clear it */
ret = mpp_buffer_group_clear(data->frm_grp);
if (ret) {
printf("clear buffer group failed ret %d\n", ret);
break;
}
}
/* Use limit config to limit buffer count to 24 with buf_size */
ret = mpp_buffer_group_limit_config(data->frm_grp, buf_size, 24);
if (ret) {
printf("limit buffer group failed ret %d\n", ret);
break;
}
/*
* All buffer group config done. Set info change ready to let
* decoder continue decoding
*/
ret = mpi->control(ctx, MPP_DEC_SET_INFO_CHANGE_READY, NULL);
if (ret) {
printf("info change ready failed ret %d\n", ret);
break;
}
} else {
err_info = mpp_frame_get_errinfo(frame) | mpp_frame_get_discard(frame);
if (err_info) {
// printf("decoder_get_frame get err info:%d discard:%d.\n",
// mpp_frame_get_errinfo(frame), mpp_frame_get_discard(frame));
}
// buf_size = mpp_frame_get_buf_size(frame);
data->frame_count++;
out_size = dump_mpp_frame_to_buf(frame,out_data);
// printf("decode_get_frame get frame %d,size:%d\n" ,data->frame_count,out_size);
}
frm_eos = mpp_frame_get_eos(frame);
mpp_frame_deinit(&frame);
frame = NULL;
get_frm = 1;
}
// try get runtime frame memory usage
if (data->frm_grp) {
size_t usage = mpp_buffer_group_usage(data->frm_grp);
if (usage > data->max_usage)
data->max_usage = usage;
}
// if last packet is send but last frame is not found continue
// if (pkt_done && !frm_eos) {
// msleep(10);
// continue;
// }
if (frm_eos) {
printf("found last frame\n");
break;
}
// if (data->frame_num > 0 && data->frame_count >= data->frame_num) {
// data->eos = 1;
// break;
// }
// if (get_frm)
// continue;
break;
} while (1);
// if (data->frame_num > 0 && data->frame_count >= data->frame_num) {
// data->eos = 1;
// printf("reach max frame number %d\n", data->frame_count);
// break;
// }
if (pkt_done)
break;
/*
* why sleep here:
* mpi->decode_put_packet will failed when packet in internal queue is
* full,waiting the package is consumed .Usually hardware decode one
* frame which resolution is 1080p needs 2 ms,so here we sleep 3ms
* * is enough.
*/
msleep(3);
} while (1);
return out_size;
}
static int mpiH264Decode(H264Decode *This,unsigned char *in_data,int in_size,unsigned char *out_data,int *out_w,int *out_h)
{
int sps_length = 0,pps_length = 0;
int frame_type = split_h264_separate(in_data,in_size,&sps_length,&pps_length);
if (frame_type == 7) {
if (memcmp(h264_sps_pps,in_data,sps_length)) {
my_h264dec->unInit(my_h264dec);
my_h264dec->init(my_h264dec,1024,600);
memcpy(h264_sps_pps,in_data,sps_length);
}
}
memset(buf,0,MPI_DEC_STREAM_SIZE);
return decode_simple(&data,in_data,in_size,out_data,out_w,out_h);
}
static int mpiH264DecInit(H264Decode *This,int width,int height)
{
MPP_RET ret = MPP_OK;
RK_U32 need_split = 1;
memset(&data, 0, sizeof(data));
data.mpi = mpi;
data.eos = 0;
data.packet = packet;
data.frame = frame;
data.frame_count = 0;
buf = mpp_malloc(char, MPI_DEC_STREAM_SIZE);
if (NULL == buf) {
printf("mpi_dec_test malloc input stream buffer failed\n");
return -1;
}
ret = mpp_packet_init(&packet, buf, MPI_DEC_STREAM_SIZE);
if (ret) {
printf("mpp_packet_init failed\n");
return -1;
}
ret = mpp_create(&ctx, &mpi);
if (MPP_OK != ret) {
printf("mpp_create failed\n");
return -1;
}
// NOTE: decoder split mode need to be set before init
MppParam param = &need_split;
ret = mpi->control(ctx, MPP_DEC_SET_PARSER_SPLIT_MODE, param);
if (MPP_OK != ret) {
printf("mpi->control failed\n");
mpp_destroy(ctx);
return -1;
}
ret = mpp_init(ctx, MPP_CTX_DEC, MPP_VIDEO_CodingAVC);
if (MPP_OK != ret) {
printf("mpp_init failed\n");
mpp_destroy(ctx);
return -1;
}
return 0;
}
static int mpiH264DecUnInit(H264Decode *This)
{
// MPP_RET ret = mpi->reset(ctx);
// if (MPP_OK != ret) {
// printf("mpi->reset failed\n");
// return -1;
// }
if (packet) {
mpp_packet_deinit(&packet);
packet = NULL;
}
if (ctx) {
mpi->reset(ctx);
mpp_destroy(ctx);
ctx = NULL;
}
if (buf) {
mpp_free(buf);
buf = NULL;
}
if (data.frm_grp) {
mpp_buffer_group_put(data.frm_grp);
data.frm_grp = NULL;
}
memset(h264_sps_pps,0,sizeof(h264_sps_pps));
return 0;
}
#if 0
void myH264DecInit(void)
{
my_h264dec = (H264Decode *)calloc(1,sizeof(H264Decode));
my_h264dec->init = mpiH264DecInit;
my_h264dec->unInit = mpiH264DecUnInit;
my_h264dec->decode = mpiH264Decode;
}
#endif
<file_sep>/src/gui/form_base.c
/*
* =============================================================================
*
* Filename: FormBase.c
*
* Description: 设置类基本窗口框架
*
* Version: 1.0
* Created: 2016-02-19 15:22:58
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include "screen.h"
#include "externfunc.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_BASE > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static int formBaseProc(FormBase *this,HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case MSG_INITDIALOG:
{
Screen.Add(hDlg,this->priv->name);
this->hDlg = hDlg;
this->priv->auto_close_time = this->priv->auto_close_time_set;
if (this->priv->initPara)
this->priv->initPara(hDlg,message,wParam,lParam);
SetTimer(hDlg,this->priv->idc_timer,FORM_TIMER_1S);
} return FORM_CONTINUE;
case MSG_MOUSEMOVE:
case MSG_LBUTTONDOWN:
{
this->priv->auto_close_time = this->priv->auto_close_time_set;
// screensaverStart(LCD_ON);
} return FORM_CONTINUE;
case MSG_TIMER:
{
if (wParam != (WPARAM)this->priv->idc_timer){
return FORM_CONTINUE;
}
if (this->priv->auto_close_time > 0) {
// printf("[%s]auto close:%d\n", this->priv->name,this->priv->auto_close_time);
if (--this->priv->auto_close_time == 0) {
// SendMessage(hDlg, MSG_CLOSE,0,0);
ShowWindow(hDlg,SW_HIDE);
}
}
} return FORM_CONTINUE;
case MSG_SHOWWINDOW:
{
if (wParam == SW_HIDE) {
this->priv->auto_close_time = 0;
if(this->priv->callBack)
this->priv->callBack();
} else if (wParam == SW_SHOWNORMAL) {
this->priv->auto_close_time = this->priv->auto_close_time_set;
}
}return FORM_CONTINUE;
case MSG_ERASEBKGND:
{
drawBackground(hDlg,
(HDC)wParam,
(const RECT*)lParam, this->priv->bmp_bkg,0x0);
} return FORM_STOP;
case MSG_CLOSE:
{
if (IsTimerInstalled(hDlg,this->priv->idc_timer) == TRUE)
KillTimer (hDlg,this->priv->idc_timer);
DestroyMainWindow (hDlg);
MainWindowThreadCleanup (hDlg);
} return FORM_STOP;
case MSG_DESTROY:
{
Screen.Del(hDlg);
DestroyAllControls(hDlg);
} return FORM_STOP;
default:
return FORM_CONTINUE;
}
}
FormBase * formBaseCreate(FormBasePriv *priv)
{
FormBase *this = (FormBase *) calloc (1,sizeof(FormBase));
this->priv = (FormBasePriv *) calloc (1,sizeof(FormBasePriv));
this->priv = priv;
this->baseProc = formBaseProc;
if (priv->auto_close_time_set == 0)
this->priv->auto_close_time_set = FORM_SETTING_ONTIME;
return this;
}
<file_sep>/src/gui/form_setting_capture_video.c
/*
* =============================================================================
*
* Filename: form_setting_CaptureVideo.c
*
* Description: CaptureVideo设置界面
*
* Version: 1.0
* Created: 2019-12-05 23:32:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <string.h>
#include "externfunc.h"
#include "screen.h"
#include "my_button.h"
#include "my_title.h"
#include "config.h"
#include "my_face.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formSettingCaptureVideoProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void loadCaptureVideoData(void);
static void buttonNotify(HWND hwnd, int id, int nc, DWORD add_data);
static int buttonSwitchCaptureNotify(HWND hwnd,void (*callback)(void));
static int buttonSwitchVideoNotify(HWND hwnd,void (*callback)(void));
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_SET_LOCAL > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define BMP_LOCAL_PATH "setting/"
enum {
IDC_TIMER_1S = IDC_FORM_LOCAL_STATR,
IDC_STATIC_IMG_WARNING,
IDC_STATIC_TEXT_WARNING,
IDC_SCROLLVIEW,
IDC_BUTTON_NETX,
IDC_BUTTON_PREV,
IDC_TITLE,
};
struct ScrollviewItem {
char title[32]; // 左边标题
char text[32]; // 右边文字
int (*callback)(HWND,void (*callback)(void)); // 点击回调函数
int index; // 元素位置
int item_type; // 0标准 1开关
int switch_state; // 当item_type为1时,此变量有效,0关闭,1开启
int changed; // 当开关变化后为1,否则为0
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static BITMAP bmp_enter; // 进入
static BITMAP image_swich_off;// 关闭状态图片
static BITMAP image_swich_on; // 打开状态图片
static HWND hScrollView;
static int bmp_load_finished = 0;
static int flag_timer_stop = 0;
// static struct ScrollviewItem *locoal_list;
// TEST
static struct ScrollviewItem locoal_list[] = {
{"拍照","",buttonSwitchCaptureNotify},
{"录像","",buttonSwitchVideoNotify},
{" ","",NULL},
{"拍照设置","",NULL},
{0},
};
static BmpLocation bmp_load[] = {
{&bmp_enter, BMP_LOCAL_PATH"ico_返回_1.png"},
{&image_swich_off,BMP_LOCAL_PATH"ico_check_nor.png"},
{&image_swich_on, BMP_LOCAL_PATH"ico_check_pre.png"},
{NULL},
};
static MY_CTRLDATA ChildCtrls [] = {
SCROLLVIEW(0,40,1024,580,IDC_SCROLLVIEW),
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
// WS_EX_AUTOSECONDARYDC,
WS_EX_NONE,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "FsetCaptureVideo",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formSettingCaptureVideoProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
};
static MyCtrlButton ctrls_button[] = {
{0},
};
static MyCtrlTitle ctrls_title[] = {
{
IDC_TITLE,
MYTITLE_LEFT_EXIT,
MYTITLE_RIGHT_NULL,
0,0,1024,40,
"拍照录像设置",
"",
0xffffff, 0x333333FF,
buttonNotify,
},
{0},
};
static FormBase* form_base = NULL;
static void enableAutoClose(void)
{
Screen.setCurrent(form_base_priv.name);
flag_timer_stop = 0;
loadCaptureVideoData();
}
/* ----------------------------------------------------------------*/
/**
* @brief buttonNotify 退出按钮
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ----------------------------------------------------------------*/
static void buttonNotify(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc == MYTITLE_BUTTON_EXIT)
ShowWindow(GetParent(hwnd),SW_HIDE);
}
static int buttonSwitchCaptureNotify(HWND hwnd,void (*callback)(void))
{
ConfigSavePublic();
loadCaptureVideoData();
}
static int buttonSwitchVideoNotify(HWND hwnd,void (*callback)(void))
{
}
/* ---------------------------------------------------------------------------*/
/**
* @brief scrollviewNotify
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ---------------------------------------------------------------------------*/
static void scrollviewNotify(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != SVN_CLICKED)
return;
int idx = SendMessage (hScrollView, SVM_GETCURSEL, 0, 0);
struct ScrollviewItem *plist;
plist = (struct ScrollviewItem *)SendMessage (hScrollView, SVM_GETITEMADDDATA, idx, 0);
if (!plist)
return;
if (!plist->callback)
return;
if (plist->item_type == 0) {
flag_timer_stop = 1;
plist->callback(hwnd,enableAutoClose);
} else if (plist->item_type == 1){
plist->switch_state ^= 1;
plist->callback(plist->switch_state,NULL);
InvalidateRect (hwnd, NULL, TRUE);
}
}
void formSettingCaptureVideoLoadBmp(void)
{
if (bmp_load_finished == 1)
return;
printf("[%s]\n", __FUNCTION__);
bmpsLoad(bmp_load);
bmp_load_finished = 1;
}
static void myDrawItem (HWND hWnd, HSVITEM hsvi, HDC hdc, RECT *rcDraw)
{
#define FILL_BMP_STRUCT(left,top,img) \
FillBoxWithBitmap(hdc,left, top,img.bmWidth,img.bmHeight,&img)
#define DRAW_TABLE(rc,offset,color) \
do { \
SetPenColor (hdc, color); \
if (p_item->index) { \
MoveTo (hdc, rc->left + offset, rc->top); \
LineTo (hdc, rc->right,rc->top); \
} \
MoveTo (hdc, rc->left + offset, rc->bottom); \
LineTo (hdc, rc->right,rc->bottom); \
} while (0)
struct ScrollviewItem *p_item = (struct ScrollviewItem *)scrollview_get_item_adddata (hsvi);
SetBkMode (hdc, BM_TRANSPARENT);
SetTextColor (hdc, PIXEL_lightwhite);
SelectFont (hdc, font20);
if (p_item->callback && p_item->item_type == 0)
FILL_BMP_STRUCT(rcDraw->left + 968,rcDraw->top + 15,bmp_enter);
// 绘制表格
DRAW_TABLE(rcDraw,0,0xCCCCCC);
// 输出文字
TextOut (hdc, rcDraw->left + 30, rcDraw->top + 15, p_item->title);
RECT rc;
memcpy(&rc,rcDraw,sizeof(RECT));
rc.left += 512;
rc.right -= 70;
SetTextColor (hdc, 0xCCCCCC);
DrawText (hdc,p_item->text, -1, &rc,
DT_VCENTER | DT_RIGHT | DT_WORDBREAK | DT_SINGLELINE);
if (p_item->item_type == 1) {
rc.left += 512;
rc.right -= 70;
if (p_item->switch_state) {
if (p_item->changed) {
rc.left -= 252;
rc.right += 412;
DrawText (hdc,"打开(需等待重启生效)", -1, &rc,
DT_VCENTER | DT_LEFT | DT_WORDBREAK | DT_SINGLELINE);
} else
DrawText (hdc,"打开", -1, &rc,
DT_VCENTER | DT_LEFT | DT_WORDBREAK | DT_SINGLELINE);
FILL_BMP_STRUCT(rcDraw->left + 968,rcDraw->top + 20,image_swich_on);
} else {
DrawText (hdc,"关闭", -1, &rc,
DT_VCENTER | DT_LEFT | DT_WORDBREAK | DT_SINGLELINE);
FILL_BMP_STRUCT(rcDraw->left + 968,rcDraw->top + 20,image_swich_off);
}
}
}
static void loadCaptureVideoData(void)
{
int i;
SVITEMINFO svii;
struct ScrollviewItem *plist = locoal_list;
SendMessage (hScrollView, SVM_RESETCONTENT, 0, 0);
for (i=0; plist->title[0] != 0; i++) {
plist->index = i;
plist->item_type = 0;
svii.nItemHeight = 60;
svii.addData = (DWORD)plist;
svii.nItem = i;
if (strcmp("设置",plist->title) == 0) {
if (g_config.cap_doorbell.type == 0) {
sprintf(plist->text,"拍照%d张",g_config.cap_doorbell.count);
} else {
sprintf(plist->text,"录像%d秒",g_config.cap_doorbell.timer);
}
}
SendMessage (hScrollView, SVM_ADDITEM, 0, (LPARAM)&svii);
SendMessage (hScrollView, SVM_SETITEMADDDATA, i, (DWORD)plist);
plist++;
}
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_title[i].idc != 0; i++) {
ctrls_title[i].font = font20;
createMyTitle(hDlg,&ctrls_title[i]);
}
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
createMyButton(hDlg,&ctrls_button[i]);
}
hScrollView = GetDlgItem (hDlg, IDC_SCROLLVIEW);
SendMessage (hScrollView, SVM_SETITEMDRAW, 0, (LPARAM)myDrawItem);
loadCaptureVideoData();
}
/* ----------------------------------------------------------------*/
/**
* @brief formSettingCaptureVideoProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ----------------------------------------------------------------*/
static int formSettingCaptureVideoProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
switch(message) // 自定义消息
{
case MSG_TIMER:
{
if (flag_timer_stop)
return 0;
} break;
case MSG_COMMAND:
{
int id = LOWORD (wParam);
int code = HIWORD (wParam);
scrollviewNotify(hDlg,id,code,0);
break;
}
case MSG_ENABLE_WINDOW:
enableAutoClose();
break;
case MSG_DISABLE_WINDOW:
flag_timer_stop = 1;
break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormSettingCaptureVideo(HWND hMainWnd,void (*callback)(void))
{
HWND Form = Screen.Find(form_base_priv.name);
if(Form) {
Screen.setCurrent(form_base_priv.name);
loadCaptureVideoData();
ShowWindow(Form,SW_SHOWNORMAL);
} else {
if (bmp_load_finished == 0) {
return 0;
}
form_base_priv.callBack = callback;
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
<file_sep>/src/app/rdface/video_ion_alloc.h
#ifndef __VIDEO_ION_ALLOC_H__
#define __VIDEO_ION_ALLOC_H__
//#include <ion/ion.h>
#include "rk_fb/rk_fb.h"
int video_ion_alloc(struct video_ion* video_ion, int width, int height);
int video_ion_alloc_rational(struct video_ion* video_ion,
int width,
int height,
int num,
int den);
int video_ion_free(struct video_ion* video_ion);
void video_ion_buffer_black(struct video_ion* video_ion, int w, int h);
#endif
<file_sep>/src/wireless/remotefile.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <stdarg.h>
#include <dirent.h>
#include "tcp_client.h"
#include "remotefile.h"
#define MyPostMessage
#define tcpclient This->Private->client
typedef struct
{
int Cmd; //open , delete
int Mode; //1 读 2写 3读写
int FileNameLen; // filename size
char FileName[1]; // filename
}FILE_OPEN_STRUCT;
// operate
enum {FILE_OPEN,FILE_DELETE,FILE_DOWNLOAD};
enum {FILE_READ,FILE_WRITE,FILE_SEEK,FILE_SETEND,FILE_CLOSE};
// file read
typedef struct
{
int Cmd; //FILE_READ
int ReadSize; //Read Size
}FILE_READ_STRUCT;
// file read return
typedef struct
{
int Size;
int Data[1];
}FILE_RET_READ;
// file write head
// return successful is writebyte, or fail is zero.
typedef struct
{
int Cmd; //FILE_WRITE
int WriteSize;
}FILE_WRITE_STRUCT;
// file seek
// return file new postion;
typedef struct
{
int Cmd; //FILE_SEEK
int offset;
int origin; // 0 file_begin, 1 file_curren, 2 file_end
}FILE_SEEK_STRUCT;
// set end of file
// return 1 if success, 0 if fail;
typedef struct
{
int Cmd; //FILE_SETEND
}FILE_SETEND_STRUCT;
struct RemoteFilePrivate //私有数据
{
char TmpFile[64];
char IP[64];
BOOL IsOpen;
int Pos;
TTCPClient *client;
};
int ExcuteCmd(int bWait,char *Cmd,...)
{
int i;
FILE *fp;
int ret;
va_list argp;
char *argv;
char commond[512] = {0};
strcat(commond,Cmd);
va_start( argp, Cmd);
for(i=1;i<20;i++) {
argv = va_arg(argp,char *);
if(argv == NULL)
break;
strcat(commond," ");
strcat(commond,argv);
}
va_end(argp);
printf("cmd :%s\n",commond);
if ((fp = popen(commond, "r") ) == 0) {
perror("popen");
return -1;
}
if ( (ret = pclose(fp)) == -1 ) {
printf("close popen file pointer fp error!\n");
// printf("popen ret is :%d\n", ret);
}
return ret;
// 用此函数导致产生僵尸进程
// system(commond);
// return 0;
}
//---------------------------------------------------------------------------
int ChangeFileName(TRemoteFile * This,char *NewName,const char *FileName)
{
int k=strlen(FileName)-1;
if(k<=0)
return 0;
while(k>0) {
if(FileName[k]=='/' || FileName[k]=='\\')
break;
k--;
}
if(k==0) {
strcpy(NewName,This->Private->TmpFile);
return 1;
}
strncpy(NewName,FileName,k+1);
strcpy(&NewName[k+1],This->Private->TmpFile);
return 1;
}
//---------------------------------------------------------------------------
static int RemoteFile_Download(TRemoteFile * This,unsigned int hWnd,const char *SrcFile,
const char *DstFile,int ExecuteMode,UpdateFunc callback)
{
int FailState;
int Pos,LastPos=0;
int filesize,iRet,readpos,readsize;
FILE *hFile;
char NewFileName[1024];
char cBuf[1024];
FILE_OPEN_STRUCT *pBuf = (FILE_OPEN_STRUCT*)cBuf;
if(This->Private->IsOpen){
This->Close(This);
}
tcpclient = TTCPClient_Create();
if(tcpclient==NULL) {
printf("RemoteFile:TCPClient Create fail!\n");
if (callback)
callback(UPDATE_FAIL,UPDATE_FAIL_REASON_CREATE);
return FALSE;
}
if(tcpclient->Connect(tcpclient,This->Private->IP,7893,2000)!=0) {
//重试
if(tcpclient->Connect(tcpclient,This->Private->IP,7893,2000)!=0) {
printf("RemoteFile:connect %s fail!\n",This->Private->IP);
FailState = UPDATE_FAIL_REASON_CONNECT;
goto error;
}
}
pBuf->Cmd = FILE_DOWNLOAD;
pBuf->FileNameLen = strlen(SrcFile)+1;
if(pBuf->FileNameLen>(512-12)) {
printf("RemoteFile:filename %s is too length!\n",SrcFile);
FailState = UPDATE_FAIL_REASON_FILENAME;
goto error;
}
pBuf->Mode = 0;
strcpy(pBuf->FileName,SrcFile);
tcpclient->SendBuffer(tcpclient,cBuf,12+pBuf->FileNameLen);
//printf("Jack : remotefile size = %d\n",filesize);
int tmp = 0;
filesize = 0;
if(tmp = tcpclient->RecvBuffer(tcpclient,&filesize,sizeof(filesize),3000)!=sizeof(filesize)) {
printf("RemoteFile:Open file Recv Data Error! tmp = %d, size = %d\n",tmp,(filesize));
FailState = UPDATE_FAIL_REASON_RECV;
goto error;
}
if(filesize<0) {
printf("RemoteFile:[%s] Return filesize %d is Fail!\n",SrcFile,filesize);
FailState = UPDATE_FAIL_REASON_RECVSIZE;
goto error;
}
This->Private->Pos = 0;
//先保存到临时文件
if(ChangeFileName(This,NewFileName,DstFile)==0) {
FailState = UPDATE_FAIL_REASON_FILENAME;
goto error;
}
//保存文件
if((hFile=fopen(NewFileName,"wb"))==NULL) {
printf("Open %s to write error!\n",NewFileName);
FailState = UPDATE_FAIL_REASON_OPEN;
goto error;
}
readpos = 0;
while(readpos<filesize) {
if(filesize-readpos>1024)
readsize = 1024;
else
readsize = filesize-readpos;
iRet = tcpclient->RecvBuffer(tcpclient,cBuf,readsize,3000);
if(readsize!=iRet) {
printf("Want read size %d, Real read size %d, Abort!\n",readsize,iRet);
break;
}
readpos+=readsize;
iRet = fwrite(cBuf,1,readsize,hFile);
if(iRet!=readsize) {
printf("Want write size %d, Real write size %d, Abort!\n",readsize,iRet);
break;
}
Pos = readpos*100/filesize;
if(Pos!=LastPos) {
LastPos = Pos;
if (callback)
callback(UPDATE_POSITION,Pos);
}
}
fflush(hFile);
fclose(hFile);
tcpclient->Destroy(tcpclient);
if(readpos==filesize) {
remove(DstFile);
if(rename(NewFileName,DstFile)==-1) {
printf("ChangeFileName %s error\n",DstFile);
FailState = UPDATE_FAIL_REASON_RENAME;
goto error;
}
if(ExecuteMode) {
ExcuteCmd(1,"chmod","+x",DstFile,NULL);
}
printf("Receive %s success\n",SrcFile);
if (callback)
callback(UPDATE_SUCCESS,0);
return TRUE;
}
else {
printf("Receive %s abort!\n",SrcFile);
FailState = UPDATE_FAIL_REASON_ABORT;
goto error;
}
error:
tcpclient->Destroy(tcpclient);
if (callback)
callback(UPDATE_FAIL,FailState);
return FALSE;
}
//---------------------------------------------------------------------------
static int RemoteFile_Open(TRemoteFile * This,const char *FileName,int OpenMode)
{
int iRet;
char cBuf[256];
FILE_OPEN_STRUCT *pBuf = (FILE_OPEN_STRUCT*)cBuf;
if(This->Private->IsOpen){
This->Close(This);
}
tcpclient = TTCPClient_Create();
if(tcpclient==NULL)
return -1;
if(tcpclient->Connect(tcpclient,This->Private->IP,7893,3000)!=0) {
printf("RemoteFile:connect fail!\n");
goto error;
}
pBuf->Cmd = FILE_OPEN;
pBuf->FileNameLen = strlen(FileName)+1;
if(pBuf->FileNameLen>(256-12)) {
printf("RemoteFile:filename is too length!\n");
goto error;
}
pBuf->Mode = OpenMode;
strcpy(pBuf->FileName,FileName);
tcpclient->SendBuffer(tcpclient,cBuf,12+pBuf->FileNameLen);
if(tcpclient->RecvBuffer(tcpclient,&iRet,sizeof(iRet),3000)!=sizeof(iRet)) {
printf("RemoteFile:Open file Recv Data Error!\n");
goto error;
}
if(iRet<0) {
printf("RemoteFile:Open File is Fail!\n");
goto error;
}
This->Private->IsOpen = TRUE;
This->Private->Pos = 0;
return iRet;
error:
tcpclient->Destroy(tcpclient);
return -1;
}
//---------------------------------------------------------------------------
static int RemoteFile_Read(TRemoteFile * This,void *Buffer,int Size)
{
int RetSize;
FILE_READ_STRUCT fileread;
if(!This->Private->IsOpen)
return 0;
if(Size<1 && Size>1024*1024)
return -1;
fileread.Cmd = FILE_READ;
fileread.ReadSize = Size;
tcpclient->SendBuffer(tcpclient,&fileread,sizeof(FILE_READ_STRUCT));
if(tcpclient->RecvBuffer(tcpclient,&RetSize,sizeof(int),2000)!=sizeof(int))
return 0;
if(tcpclient->RecvBuffer(tcpclient,Buffer,RetSize,2000)!=RetSize)
return 0;
This->Private->Pos+=RetSize;
return RetSize;
}
//---------------------------------------------------------------------------
static BOOL RemoteFile_Write(TRemoteFile * This,void *Buffer,int Size)
{
BOOL RetVal;
FILE_WRITE_STRUCT filewrite;
if(!This->Private->IsOpen)
return FALSE;
filewrite.Cmd = FILE_WRITE;
filewrite.WriteSize = Size;
tcpclient->SendBuffer(tcpclient,&filewrite,sizeof(FILE_WRITE_STRUCT));
if(tcpclient->SendBuffer(tcpclient,Buffer,Size)!=Size)
return FALSE;
if(tcpclient->RecvBuffer(tcpclient,&RetVal,sizeof(RetVal),1500)!=sizeof(RetVal))
return FALSE;
if(RetVal)
This->Private->Pos+=Size;
return RetVal;
}
//---------------------------------------------------------------------------
static int RemoteFile_Seek(TRemoteFile * This,int offset,int origin)
{
int NewPos;
FILE_SEEK_STRUCT fileseek;
if(!This->Private->IsOpen)
return FALSE;
fileseek.Cmd = FILE_SEEK;
fileseek.offset = offset;
fileseek.origin = origin;
if(tcpclient->SendBuffer(tcpclient,&fileseek,sizeof(FILE_SEEK_STRUCT))!=sizeof(FILE_SEEK_STRUCT))
return -1;
if(tcpclient->RecvBuffer(tcpclient,&NewPos,sizeof(NewPos),1000)!=sizeof(NewPos))
return -1;
This->Private->Pos = NewPos;
return NewPos;
}
//---------------------------------------------------------------------------
static BOOL RemoteFile_SetEnd(TRemoteFile * This)
{
BOOL RetVal;
FILE_SETEND_STRUCT filesetend;
if(!This->Private->IsOpen)
return FALSE;
filesetend.Cmd = FILE_SETEND;
if(tcpclient->SendBuffer(tcpclient,&filesetend,sizeof(FILE_SETEND_STRUCT))!=sizeof(FILE_SETEND_STRUCT))
return FALSE;
if(tcpclient->RecvBuffer(tcpclient,&RetVal,sizeof(RetVal),1000)!=sizeof(RetVal))
return FALSE;
return RetVal;
}
//---------------------------------------------------------------------------
static int RemoteFile_GetPos(TRemoteFile * This)
{
return This->Private->Pos;
}
//---------------------------------------------------------------------------
static void RemoteFile_Close(TRemoteFile * This)
{
if(This->Private->IsOpen){
BOOL Cmd = FILE_CLOSE;
This->Private->IsOpen = FALSE;
tcpclient->SendBuffer(tcpclient,&Cmd,sizeof(Cmd));
tcpclient->Destroy(tcpclient);
}
}
//---------------------------------------------------------------------------
static void RemoteFile_Destroy(TRemoteFile * This)
{
This->Close(This);
free(This->Private);
free(This);
}
//---------------------------------------------------------------------------
TRemoteFile * CreateRemoteFile(const char *IP,const char *TempFile)
{
TRemoteFile * This = (TRemoteFile*)malloc(sizeof(TRemoteFile));
if(This==NULL) {
printf("alloc TRemoteFile memory failt!\n");
return NULL;
}
This->Private = (struct RemoteFilePrivate*)malloc(sizeof(struct RemoteFilePrivate));
if(This->Private==NULL) {
free(This);
printf("alloc TRemoteFile memory failt!\n");
return NULL;
}
memset(This->Private,0,sizeof(struct RemoteFilePrivate));
strncpy(This->Private->IP,IP,sizeof(This->Private->IP)-1);
strncpy(This->Private->TmpFile,TempFile,(sizeof(This->Private->TmpFile))-1);
This->Open = RemoteFile_Open;
This->Download = RemoteFile_Download;
This->Read = RemoteFile_Read;
This->Write = RemoteFile_Write;
This->Seek = RemoteFile_Seek;
This->SetEnd = RemoteFile_SetEnd;
This->GetPos = RemoteFile_GetPos;
This->Close = RemoteFile_Close;
This->Destroy = RemoteFile_Destroy;
return This;
}
//---------------------------------------------------------------------------
<file_sep>/src/wireless/udp_server.h
/*
* =============================================================================
*
* Filename: UDPServer.h
*
* Description: udpÇý¶¯
*
* Version: 1.0
* Created: 2018-03-05 17:31:34
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _UDPSERVER_H
#define _UDPSERVER_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <stdint.h>
#define MSG_SENDSUCCESS 1 //wParam
#define MSG_SENDTIMEOUT 2 //wParam
typedef struct _SocketHandle {
char IP[16];
int Port;
} SocketHandle;
typedef struct _SocketPacket {
int Size;
char Data[1];
} SocketPacket;
typedef struct _UdpSocket {
int handle;
SocketHandle *ABinding;
SocketPacket *AData;
}UdpSocket;
typedef void (*CallBackUDP)(int Ret,void *CallBackData);
struct _UdpServerPriv;
typedef struct _TUDPServer {
struct _UdpServerPriv *priv;
void (* Destroy)(struct _TUDPServer *This);
int (* RecvBuffer)(struct _TUDPServer *This,void *buf,int count,int TimeOut,
void * from,int * fromlen);
int (* SendBuffer)(struct _TUDPServer *This,const char *IP,int port,const void *buf,int count);
void (*AddTask)(struct _TUDPServer *This,const char *IP,int Port,void *pData,int Size,int Times,
CallBackUDP Func,void *CallBackData);
void (*KillTask)(struct _TUDPServer *This,const char *IP,int Port);
int (*KillTaskCondition)(struct _TUDPServer* This,int (*condition)(void *arg1,void *arg2),void *arg);
void (*udpSocketRead)(SocketHandle *ABinding,SocketPacket *AData);
} TUDPServer;
TUDPServer* udpServerCreate(int Port,const char *queue_name);
void udpServerInit(void (*udpSocketRead)(SocketHandle *ABinding,SocketPacket *AData),
int port);
extern TUDPServer *udp_server;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/module/updater/verify/crc/crc32.cpp
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include "crc32.h"
unsigned int RKCRC::gTable_Crc32[256] = {
0x00000000, 0x04c10db7, 0x09821b6e, 0x0d4316d9,
0x130436dc, 0x17c53b6b, 0x1a862db2, 0x1e472005,
0x26086db8, 0x22c9600f, 0x2f8a76d6, 0x2b4b7b61,
0x350c5b64, 0x31cd56d3, 0x3c8e400a, 0x384f4dbd,
0x4c10db70, 0x48d1d6c7, 0x4592c01e, 0x4153cda9,
0x5f14edac, 0x5bd5e01b, 0x5696f6c2, 0x5257fb75,
0x6a18b6c8, 0x6ed9bb7f, 0x639aada6, 0x675ba011,
0x791c8014, 0x7ddd8da3, 0x709e9b7a, 0x745f96cd,
0x9821b6e0, 0x9ce0bb57, 0x91a3ad8e, 0x9562a039,
0x8b25803c, 0x8fe48d8b, 0x82a79b52, 0x866696e5,
0xbe29db58, 0xbae8d6ef, 0xb7abc036, 0xb36acd81,
0xad2ded84, 0xa9ece033, 0xa4aff6ea, 0xa06efb5d,
0xd4316d90, 0xd0f06027, 0xddb376fe, 0xd9727b49,
0xc7355b4c, 0xc3f456fb, 0xceb74022, 0xca764d95,
0xf2390028, 0xf6f80d9f, 0xfbbb1b46, 0xff7a16f1,
0xe13d36f4, 0xe5fc3b43, 0xe8bf2d9a, 0xec7e202d,
0x34826077, 0x30436dc0, 0x3d007b19, 0x39c176ae,
0x278656ab, 0x23475b1c, 0x2e044dc5, 0x2ac54072,
0x128a0dcf, 0x164b0078, 0x1b0816a1, 0x1fc91b16,
0x018e3b13, 0x054f36a4, 0x080c207d, 0x0ccd2dca,
0x7892bb07, 0x7c53b6b0, 0x7110a069, 0x75d1adde,
0x6b968ddb, 0x6f57806c, 0x621496b5, 0x66d59b02,
0x5e9ad6bf, 0x5a5bdb08, 0x5718cdd1, 0x53d9c066,
0x4d9ee063, 0x495fedd4, 0x441cfb0d, 0x40ddf6ba,
0xaca3d697, 0xa862db20, 0xa521cdf9, 0xa1e0c04e,
0xbfa7e04b, 0xbb66edfc, 0xb625fb25, 0xb2e4f692,
0x8aabbb2f, 0x8e6ab698, 0x8329a041, 0x87e8adf6,
0x99af8df3, 0x9d6e8044, 0x902d969d, 0x94ec9b2a,
0xe0b30de7, 0xe4720050, 0xe9311689, 0xedf01b3e,
0xf3b73b3b, 0xf776368c, 0xfa352055, 0xfef42de2,
0xc6bb605f, 0xc27a6de8, 0xcf397b31, 0xcbf87686,
0xd5bf5683, 0xd17e5b34, 0xdc3d4ded, 0xd8fc405a,
0x6904c0ee, 0x6dc5cd59, 0x6086db80, 0x6447d637,
0x7a00f632, 0x7ec1fb85, 0x7382ed5c, 0x7743e0eb,
0x4f0cad56, 0x4bcda0e1, 0x468eb638, 0x424fbb8f,
0x5c089b8a, 0x58c9963d, 0x558a80e4, 0x514b8d53,
0x25141b9e, 0x21d51629, 0x2c9600f0, 0x28570d47,
0x36102d42, 0x32d120f5, 0x3f92362c, 0x3b533b9b,
0x031c7626, 0x07dd7b91, 0x0a9e6d48, 0x0e5f60ff,
0x101840fa, 0x14d94d4d, 0x199a5b94, 0x1d5b5623,
0xf125760e, 0xf5e47bb9, 0xf8a76d60, 0xfc6660d7,
0xe22140d2, 0xe6e04d65, 0xeba35bbc, 0xef62560b,
0xd72d1bb6, 0xd3ec1601, 0xdeaf00d8, 0xda6e0d6f,
0xc4292d6a, 0xc0e820dd, 0xcdab3604, 0xc96a3bb3,
0xbd35ad7e, 0xb9f4a0c9, 0xb4b7b610, 0xb076bba7,
0xae319ba2, 0xaaf09615, 0xa7b380cc, 0xa3728d7b,
0x9b3dc0c6, 0x9ffccd71, 0x92bfdba8, 0x967ed61f,
0x8839f61a, 0x8cf8fbad, 0x81bbed74, 0x857ae0c3,
0x5d86a099, 0x5947ad2e, 0x5404bbf7, 0x50c5b640,
0x4e829645, 0x4a439bf2, 0x47008d2b, 0x43c1809c,
0x7b8ecd21, 0x7f4fc096, 0x720cd64f, 0x76cddbf8,
0x688afbfd, 0x6c4bf64a, 0x6108e093, 0x65c9ed24,
0x11967be9, 0x1557765e, 0x18146087, 0x1cd56d30,
0x02924d35, 0x06534082, 0x0b10565b, 0x0fd15bec,
0x379e1651, 0x335f1be6, 0x3e1c0d3f, 0x3add0088,
0x249a208d, 0x205b2d3a, 0x2d183be3, 0x29d93654,
0xc5a71679, 0xc1661bce, 0xcc250d17, 0xc8e400a0,
0xd6a320a5, 0xd2622d12, 0xdf213bcb, 0xdbe0367c,
0xe3af7bc1, 0xe76e7676, 0xea2d60af, 0xeeec6d18,
0xf0ab4d1d, 0xf46a40aa, 0xf9295673, 0xfde85bc4,
0x89b7cd09, 0x8d76c0be, 0x8035d667, 0x84f4dbd0,
0x9ab3fbd5, 0x9e72f662, 0x9331e0bb, 0x97f0ed0c,
0xafbfa0b1, 0xab7ead06, 0xa63dbbdf, 0xa2fcb668,
0xbcbb966d, 0xb87a9bda, 0xb5398d03, 0xb1f880b4,
};
unsigned int RKCRC::CRC_32( unsigned char * aData, unsigned int aSize )
{
unsigned int i;
unsigned int nAccum = 0;
for ( i = 0; i < aSize; i++ )
nAccum = ( nAccum << 8 ) ^ gTable_Crc32[( nAccum >> 24 ) ^ *aData++];
return nAccum;
}
RKCRC::RKCRC()
{
}
RKCRC::~RKCRC()
{
}
#if 0
int main(int argc, char const *argv[])
{
unsigned int crc32 = 0;
unsigned char data[2048];
RKCRC* rkcrc = new RKCRC();
memset(data, 49, 2048);
crc32 = rkcrc->CRC_32(data, 2048);
printf("vicent --------------- crc32 %x\n", crc32);
memset(data, 49, 2048);
crc32 = rkcrc->CRC_32(data, 2048);
printf("vicent --------------- crc32 %x\n", crc32);
memset(data, 45, 2048);
crc32 = rkcrc->CRC_32(data, 2048);
printf("vicent --------------- crc32 %x\n", crc32);
memset(data, 48, 2048);
crc32 = rkcrc->CRC_32(data, 2048);
printf("vicent --------------- crc32 %x\n", crc32);
delete rkcrc;
rkcrc = NULL;
return 0;
}
#endif
<file_sep>/module/video/process/md_encoder_process.h
#ifndef _ENCODER_PROCESS_H
#define _ENCODER_PROCESS_H
#include <CameraHal/StrmPUBase.h>
#include <easymedia/encoder.h>
#include <easymedia/buffer.h>
#include <easymedia/image.h>
#include <adk/mm/buffer.h>
typedef void (*EncCallbackFunc)(void *data,int size,int frame_type);
typedef void (*RecordStopCallbackFunc)(void);
class H264Encoder : public StreamPUBase {
public:
H264Encoder();
virtual ~H264Encoder();
bool processFrame(std::shared_ptr<BufferBase> inBuf,
std::shared_ptr<BufferBase> outBuf) override;
int startEnc(int width,int height,EncCallbackFunc encCallback);
int stopEnc(void);
void recordStart(EncCallbackFunc recordCallback);
void recordSetStopFunc(RecordStopCallbackFunc recordCallback);
void recordStop(void);
FILE* fd(void) const {
return fd_;
}
bool start_enc(void) const {
return start_enc_;
};
bool start_record(void) const {
return start_record_;
};
int getWidth(void) const {
return width_;
}
int getHeight(void) const {
return height_;
}
EncCallbackFunc encCallback(void) const {
return encCallback_;
};
EncCallbackFunc recordCallback(void) const {
return recordCallback_;
};
RecordStopCallbackFunc recordStopCallback(void) const {
return recordStopCallback_;
};
private:
FILE* fd_;
bool start_enc_;
bool start_record_;
bool last_frame_;
int width_;
int height_;
EncCallbackFunc encCallback_;
EncCallbackFunc recordCallback_;
RecordStopCallbackFunc recordStopCallback_;
};
#endif // ENCODER_
<file_sep>/src/gui/form_setting_store.c
/*
* =============================================================================
*
* Filename: form_setting_Store.c
*
* Description: Store设置界面
*
* Version: 1.0
* Created: 2018-03-01 23:32:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <string.h>
#include "externfunc.h"
#include "screen.h"
#include "my_title.h"
#include "config.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formSettingStoreProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void buttonNotify(HWND hwnd, int id, int nc, DWORD add_data);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_SET_LOCAL > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define BMP_LOCAL_PATH "setting/"
enum {
IDC_TIMER_1S = IDC_FORM_STORE_STATR,
IDC_SCROLLVIEW,
IDC_TITLE,
};
struct ScrollviewItem {
char title[32]; // 左边标题
char text[32]; // 右边文字
void (*callback)(void); // 点击回调函数
int index; // 元素位置
};
struct MemData {
char total[32];
char residue[32];
char used[32];
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static HWND hScrollView;
static int bmp_load_finished = 0;
static int flag_timer_stop = 0;
struct MemData mem_data;
// static struct ScrollviewItem *locoal_list;
// TEST
static struct ScrollviewItem locoal_list[] = {
{"总空间", "",NULL},
{"剩余空间","",NULL},
{"已用比例","",NULL},
{0},
};
static BITMAP bmp_warning; // 警告
static BITMAP bmp_security; // 加密
static BITMAP bmp_select; // 选中
static BITMAP bmp_enter; // 进入
static BmpLocation bmp_load[] = {
{&bmp_enter, BMP_LOCAL_PATH"ico_返回_1.png"},
{NULL},
};
static MY_CTRLDATA ChildCtrls [] = {
SCROLLVIEW(0,40,1024,580,IDC_SCROLLVIEW),
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
// WS_EX_AUTOSECONDARYDC,
WS_EX_NONE,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "FsetStore",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formSettingStoreProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
};
static MyCtrlTitle ctrls_title[] = {
{
IDC_TITLE,
MYTITLE_LEFT_EXIT,
MYTITLE_RIGHT_TEXT,
0,0,1024,40,
"本地存储",
"格式化",
0xffffff, 0x333333FF,
buttonNotify,
},
{0},
};
static FormBase* form_base = NULL;
static void enableAutoClose(void)
{
Screen.setCurrent(form_base_priv.name);
flag_timer_stop = 0;
}
/* ----------------------------------------------------------------*/
/**
* @brief buttonNotify 退出按钮
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ----------------------------------------------------------------*/
static void buttonNotify(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc == MYTITLE_BUTTON_EXIT)
ShowWindow(GetParent(hwnd),SW_HIDE);
}
void formSettingStoreLoadBmp(void)
{
if (bmp_load_finished == 1)
return;
printf("[%s]\n", __FUNCTION__);
bmpsLoad(bmp_load);
bmp_load_finished = 1;
}
static void myDrawItem (HWND hWnd, HSVITEM hsvi, HDC hdc, RECT *rcDraw)
{
#define FILL_BMP_STRUCT(left,top,img) \
FillBoxWithBitmap(hdc,left, top,img.bmWidth,img.bmHeight,&img)
#define DRAW_TABLE(rc,offset,color) \
do { \
SetPenColor (hdc, color); \
if (p_item->index) { \
MoveTo (hdc, rc->left + offset, rc->top); \
LineTo (hdc, rc->right,rc->top); \
} \
MoveTo (hdc, rc->left + offset, rc->bottom); \
LineTo (hdc, rc->right,rc->bottom); \
} while (0)
struct ScrollviewItem *p_item = (struct ScrollviewItem *)scrollview_get_item_adddata (hsvi);
SetBkMode (hdc, BM_TRANSPARENT);
SetTextColor (hdc, PIXEL_lightwhite);
SelectFont (hdc, font20);
FILL_BMP_STRUCT(rcDraw->left + 968,rcDraw->top + 15,bmp_enter);
// 绘制表格
DRAW_TABLE(rcDraw,0,0xCCCCCC);
// 输出文字
TextOut (hdc, rcDraw->left + 30, rcDraw->top + 15, p_item->title);
RECT rc;
memcpy(&rc,rcDraw,sizeof(RECT));
rc.left += 512;
rc.right -= 70;
SetTextColor (hdc, 0xCCCCCC);
DrawText (hdc,p_item->text, -1, &rc,
DT_VCENTER | DT_RIGHT | DT_WORDBREAK | DT_SINGLELINE);
}
static void loadStoreData(void)
{
int i;
SVITEMINFO svii;
struct ScrollviewItem *plist = locoal_list;
SendMessage (hScrollView, SVM_RESETCONTENT, 0, 0);
memset(&mem_data,0,sizeof(mem_data));
getSdMem(mem_data.total,mem_data.residue,mem_data.used);
for (i=0; plist->title[0] != 0; i++) {
plist->index = i;
svii.nItemHeight = 60;
svii.addData = (DWORD)plist;
svii.nItem = i;
if (strcmp("总空间",plist->title) == 0) {
sprintf(plist->text,"%s",mem_data.total);
} else if (strcmp("剩余空间",plist->title) == 0) {
sprintf(plist->text,"%s",mem_data.residue);
} else if (strcmp("已用比例",plist->title) == 0) {
sprintf(plist->text,"%s",mem_data.used);
}
SendMessage (hScrollView, SVM_ADDITEM, 0, (LPARAM)&svii);
SendMessage (hScrollView, SVM_SETITEMADDDATA, i, (DWORD)plist);
plist++;
}
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_title[i].idc != 0; i++) {
ctrls_title[i].font = font20;
createMyTitle(hDlg,&ctrls_title[i]);
}
hScrollView = GetDlgItem (hDlg, IDC_SCROLLVIEW);
SendMessage (hScrollView, SVM_SETITEMDRAW, 0, (LPARAM)myDrawItem);
loadStoreData();
}
/* ----------------------------------------------------------------*/
/**
* @brief formSettingStoreProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ----------------------------------------------------------------*/
static int formSettingStoreProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
switch(message) // 自定义消息
{
case MSG_TIMER:
{
if (flag_timer_stop)
return 0;
} break;
case MSG_ENABLE_WINDOW:
enableAutoClose();
break;
case MSG_DISABLE_WINDOW:
flag_timer_stop = 1;
break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormSettingStore(HWND hMainWnd,void (*callback)(void))
{
HWND Form = Screen.Find(form_base_priv.name);
if(Form) {
Screen.setCurrent(form_base_priv.name);
loadStoreData();
ShowWindow(Form,SW_SHOWNORMAL);
} else {
if (bmp_load_finished == 0) {
return 0;
}
form_base_priv.callBack = callback;
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
<file_sep>/src/app/my_update.h
/*
* =============================================================================
*
* Filename: my_update.h
*
* Description: 升级流程
*
* Version: 1.0
* Created: 2019-09-03 14:20:17
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_UPDATE_H
#define _MY_UPDATE_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
enum {
UPDATE_FAIL, // 升级失败
UPDATE_SUCCESS, // 升级成功
UPDATE_POSITION // 升级百分比
};
enum {
UPDATE_TYPE_NONE, // 无需升级
UPDATE_TYPE_SERVER, // 网络升级
UPDATE_TYPE_SDCARD, // sd卡升级
UPDATE_TYPE_CENTER, // 管理中心升级
};
typedef void (*UpdateFunc)(int result,int reason);
typedef struct _MyUpdateInterface{
void (*uiUpdateStart)(void);
void (*uiUpdateDownloadSuccess)(void);
void (*uiUpdateSuccess)(void);
void (*uiUpdateSdCard)(void);
void (*uiUpdateFail)(void);
void (*uiUpdatePos)(int pos);
void (*uiUpdateStop)(void);
}MyUpdateInterface;
struct _MyUpdatePrivate;
typedef struct _MyUpdate {
struct _MyUpdatePrivate *priv;
MyUpdateInterface *interface;
int (*init)(struct _MyUpdate *,int type,char *ip,int port,char *file_path,UpdateFunc callbackFunc);
int (*download)(struct _MyUpdate *);
int (*uninit)(struct _MyUpdate *);
/* ---------------------------------------------------------------------------*/
/**
* @brief int 是否需要升级 1是,0否
*
* @param
* @param version 需要升级时,升级后版本
* @param content 升级内容
*/
/* ---------------------------------------------------------------------------*/
int (*needUpdate)(struct _MyUpdate *,char *version,char *content);
/* ---------------------------------------------------------------------------*/
/**
* @brief int 是否正在处于升级状态
*
* @param 0否,1是
*/
/* ---------------------------------------------------------------------------*/
int (*isUpdating)(struct _MyUpdate *);
}MyUpdate;
void myUpdateInit(void);
void myUpdateStart(int type,char *ip,int port,char *file_path);
extern MyUpdate *my_update;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/protocol.h
/*
* =============================================================================
*
* Filename: protocol.h
*
* Description: 猫眼相关协议
*
* Version: 1.0
* Created: 2019-05-18 13:54:36
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _PROTOCOL_H
#define _PROTOCOL_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <stdint.h>
#include "ipc_server.h"
enum {
IPC_DEV_TYPE_MAIN,
IPC_DEV_TYPE_UART,
IPC_DEV_TYPE_VIDEO,
};
// IPC通信消息
enum {
IPC_VIDEO_ON, // 打开本地视频
IPC_VIDEO_OFF, // 关闭本地视频
IPC_VIDEO_FACE_ON, // 打开人脸识别
IPC_VIDEO_FACE_OFF, // 关闭人脸识别
IPC_VIDEO_ENCODE_ON, // 打开h264编码
IPC_VIDEO_ENCODE_OFF, // 关闭h264编码
IPC_VIDEO_DECODE_ON, // 打开h264解码
IPC_VIDEO_DECODE_OFF, // 关闭h264解码
IPC_VIDEO_CAPTURE, // 抓拍图片
IPC_VIDEO_CAPTURE_END, // 抓拍图片结束
IPC_VIDEO_RECORD_START, // 开始录像
IPC_VIDEO_RECORD_STOP, // 停止录像
IPC_UART_SLEEP, // 进入休眠
IPC_UART_KEY_POWER, // 室内机电源按键短按
IPC_UART_KEYHOME, // 室内机按键触发
IPC_UART_DOORBELL, // 门铃按键触发
IPC_UART_PIR, // 门外pir触发
IPC_UART_WIFI_WAKE, // wifi唤醒触发
IPC_UART_WIFI_RESET, // wifi复位
IPC_UART_POWEROFF, // 室内机电源键长按关机
IPC_UART_REMOVE_CAP, // 当识别到为熟人后删除门铃拍照
IPC_UART_CAPTURE, // 开机前抓拍图片
IPC_UART_GETVERSION, // 获取单片机版本信息
IPC_UART_SET_PIR, // 设置PIR强度
};
enum {
PROTOCOL_TALK_LAN, // 局域网对讲
PROTOCOL_TALK_CLOUD, // 云对讲
};
enum {
USER_TYPE_CATEYE,
USER_TYPE_OTHERS,
};
enum {
DEV_TYPE_UNDEFINED = 0, //未定义
DEV_TYPE_ENTRANCEMACHINE = 1, //智能门禁
DEV_TYPE_HOUSEHOLDAPP = 2, //住户手机APP
DEV_TYPE_INNERDOORMACHINE = 3, //室内主机
DEV_TYPE_SECURITYSTAFFAPP = 4, //保安手机APP
DEV_TYPE_HOUSEENTRANCEMACHINE = 5, //户门口机
};
enum {
CAP_TYPE_FORMMAIN = 0, // 主界面按抓拍键
CAP_TYPE_TALK, // 通话时按抓拍
CAP_TYPE_ALARM, // 徘徊报警抓拍
CAP_TYPE_FACE, // 人脸识别抓拍
CAP_TYPE_DOORBELL, // 进入主程序后抓拍
};
typedef enum _AlarmType{
ALARM_TYPE_LOWPOWER, // 低电量报警
ALARM_TYPE_PEOPLES, // 陌生人徘徊报警
}AlarmType;
typedef enum _CallDir{
CALL_DIR_IN, // 呼入
CALL_DIR_OUT, // 呼出
}CalLDir;
typedef struct _ReportAlarmData{
char date[32]; // 日期
AlarmType type; // 报警类型
int has_people; // 徘徊报警时,判断是否有人
uint64_t picture_id;// 徘徊报警时,抓拍图片
int age; // 年龄
int sex; // 性别
}ReportAlarmData;
typedef struct _ReportFaceData{
char date[32]; // 日期
uint64_t picture_id;// 识别人脸时,抓拍图片
char nick_name[32]; // 名称
char user_id[32]; // face_id
}ReportFaceData;
typedef struct _ReportTalkData{
char date[32]; // 日期
uint64_t picture_id;// 抓拍图片或录像
CalLDir call_dir; // 0呼入 1呼出
int answered; // true 接听 false未接听
int talk_time; // 通话时间
char nick_name[32]; // 通话人
}ReportTalkData;
typedef struct _ReportFactory{
char date[32]; // 日期
}ReportFactory;
typedef struct _ReportElectric{
char date[32]; // 日期
int value; // 电量百分比
}ReportElectric;
typedef struct _UpLoadData{
char file_path[64]; // 图片本地路径
uint64_t picture_id;// 徘徊报警时,抓拍图片
}UpLoadData;
typedef struct _IpcData {
int cmd;
int dev_type;
int leng;
int count;
char s_version[3];
int need_ring; // 主程序是否需要响铃声,0否,1是
int pir_strength; // pir强度
int pir_strength_result; // pir强度设置结果
union {
char array_buf[128];
char cap_path[128];
struct {
char path[64];
char date[32];
char name[32];
}file;
}data;
}IpcData;
typedef struct _UserStruct {
char id[32];
char nick_name[32];
char token[256];
int scope;
}UserStruct;
// 局域网协议
struct _ProtocolPriv;
typedef struct _Protocol {
struct _ProtocolPriv *priv;
void (*getImei)(void (*callBack)(int result));
void (*getFaceLicense)(void (*callBack)(int result));
int (*isNeedToUpdate)(char *version,char *content);
}Protocol;
extern Protocol *protocol;
// 对讲协议
typedef struct _ProtocolTalk {
int type; // 0,3000局域网对讲协议,非0其他对讲协议
void (*reload)(void);
void (*dial)(char *user_id,void (*callBack)(int result));
void (*answer)(void);
void (*hangup)(int need_transfer); // 0不需要转呼APP,1需要转呼APP
void (*connect)(void);
void (*reconnect)(void);
void (*unlock)(void);
void (*uiShowFormVideo)(int type,char *name,int dir);
void (*uiHangup)(void);
void (*uiAnswer)(char *name);
void (*sendCmd)(char *cmd,char *user_id);
void (*receivedCmd)(const char *user_id,void *arg);
void (*sendVideo)(void *data,int size);
void (*receiveVideo)(void *data,int *size);
void (*initAudio)(void);
void (*playAudio)(const char *data,unsigned int size);
void (*startRecord)(void);
void (*recording)(char *data,unsigned int size);
void (*playVideo)(const unsigned char* frame_data, const unsigned int data_len);
void (*udpCmd)(char *ip,int port, char *data,int size);
}ProtocolTalk;
extern ProtocolTalk *protocol_talk;
// 平台协议
typedef struct _ProtocolHardcloud {
void (*uploadPic)(char *path,uint64_t pic_id);
void (*reportCapture)(uint64_t pic_id);
void (*reportAlarm)(ReportAlarmData *data);
void (*reportFace)(ReportFaceData *data);
void (*reportTalk)(ReportTalkData *data);
void (*reportFactory)(ReportFactory *data);
void (*reportElectric)(ReportElectric *data);
void (*enableSleepMpde)(void);
}ProtocolHardcloud;
extern ProtocolHardcloud *protocol_hardcloud;
// 单片机协议
typedef struct _ProtocolSinglechip {
void (*deal)(IpcData *ipc_data); // 处理单片机协议
void (*cmdSleep)(void); // 发送进入睡眠模式
void (*cmdPowerOff)(void); // 发送进入关机
void (*cmdWifiReset)(void); // 复位wifi
void (*cmdGetVersion)(void); // 获取单片机版本号
void (*cmdSetPirStrength)(int strength); // 设置PIR信号强度
void (*hasPeople)(char *nick_name,char *user_id);// 人脸识别到熟人
}ProtocolSinglechip;
extern ProtocolSinglechip *protocol_singlechip;
void protocolInit(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/module/stdioredirect/CMakeLists.txt
aux_source_directory(. SRCS)
add_definitions(
-DLINUX -DSUPPORT_ION -DENABLE_ASSERT -DDEBUG
)
add_executable(red ${SRCS})
target_link_libraries(red
pthread
)
<file_sep>/src/app/udp_talk/CMakeLists.txt
STRING( REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER_APP_UDPTALK ${CMAKE_CURRENT_SOURCE_DIR})
set(SRC_APP_UDPTALK
udp_talk_protocol.c
udp_talk_transport.c
udp_talk_parse.c
udp_client.c
share_memory.c
)
add_library (${CURRENT_FOLDER_APP_UDPTALK} ${SRC_APP_UDPTALK})
<file_sep>/src/drivers/thread_helper.h
/*
* =============================================================================
*
* Filename: thread_helper.h
*
* Description: 创建线程函数,自动销毁
*
* Version: 1.0
* Created: 2019-05-25 14:05:07
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _THREAD_HELPER_H
#define _THREAD_HELPER_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <pthread.h>
#include <sys/prctl.h>
int createThread(void *(*start_routine)(void *), void *arg);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/gui/form_videolayer.h
/*
* =====================================================================================
*
* Filename: FormVideoLayer.h
*
* Description: 主窗口
*
* Version: 1.0
* Created: 2016-02-23 15:34:38
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
#ifndef _FORM_VIDEOLAYER_H
#define _FORM_VIDEOLAYER_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include "commongdi.h"
void formVideoLayerCreate(void);
void formVideoLayerScreenOn(void);
void formVideoLayerScreenOff(void);
void formVideoLayerGotoPoweroff(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/gui/form_topmessage.c
/*
* =============================================================================
*
* Filename: form_topmessage.c
*
* Description: Qrcode设置界面
*
* Version: 1.0
* Created: 2018-03-01 23:32:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <string.h>
#include "externfunc.h"
#include "screen.h"
#include "my_button.h"
#include "my_title.h"
#include "config.h"
#include "protocol.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
extern void configFactory(void);
extern void formVideoLayerGotoPoweroff(void);
extern int createFormPowerOffSleep(void);
extern int createFormPowerOffReboot(void);
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static void buttonCancel(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonConfirm(HWND hwnd, int id, int nc, DWORD add_data);
static int formTopmessageProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_SET_LOCAL > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define BMP_LOCAL_PATH "setting/"
enum {
IDC_TIMER_1S = IDC_FORM_TOPMESSAGE,
IDC_STATIC_TEXT_TITLE,
IDC_STATIC_TEXT_CONTENT,
IDC_STATIC_IMAGE_IMEI,
IDC_STATIC_IMAGE_APP_URL,
IDC_BUTTON_COMFIRM,
IDC_BUTTON_CANCEL,
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static BITMAP bmp_bkg;
static char txt_title[128],txt_content[521];
static void (*callbackConfirm)(void);
static void (*callbackCancel)(void);
static BmpLocation bmp_load[] = {
{&bmp_bkg,BMP_LOCAL_PATH"bg_fact_reset.png"},
// {&bmp_null,BMP_LOCAL_PATH"cancel_btn.png"},
// {&bmp_null,BMP_LOCAL_PATH"confirm_btn.png"},
{NULL},
};
static MY_CTRLDATA ChildCtrls [] = {
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
WS_EX_NONE,
282,160,460,280,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "FsetTopmessage",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formTopmessageProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
.bmp_bkg = &bmp_bkg,
};
static MyCtrlButton ctrls_button[] = {
{IDC_BUTTON_COMFIRM,MYBUTTON_TYPE_TWO_STATE|MYBUTTON_TYPE_TEXT_CENTER,"确认",0,230,buttonConfirm},
{IDC_BUTTON_CANCEL,MYBUTTON_TYPE_TWO_STATE|MYBUTTON_TYPE_TEXT_CENTER,"取消",231,230,buttonCancel},
{0},
};
static FormBase* form_base = NULL;
static void buttonCancel(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
if (callbackCancel)
callbackCancel();
ShowWindow(GetParent(hwnd),SW_HIDE);
}
static void buttonConfirm(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
if (callbackConfirm)
callbackConfirm();
ShowWindow(GetParent(hwnd),SW_HIDE);
}
static void paint(HWND hWnd,HDC hdc)
{
RECT rc_text;
SetTextColor(hdc,RGBA2Pixel (hdc, 0x38, 0x38, 0x38, 0xFF));
SelectFont (hdc, font20);
rc_text.left = 0;
rc_text.right = 460;
rc_text.top = 0;
rc_text.bottom = 63;
DrawText (hdc,txt_title, -1, &rc_text,
DT_CENTER | DT_VCENTER | DT_WORDBREAK | DT_SINGLELINE);
rc_text.left = 60;
rc_text.right = 400;
rc_text.bottom = 230;
if (strlen(txt_content) > 17) {
rc_text.top = 111;
DrawText (hdc,txt_content, -1, &rc_text,
DT_CENTER | DT_VCENTER | DT_WORDBREAK );
} else {
rc_text.top = 63;
DrawText (hdc,txt_content, -1, &rc_text,
DT_CENTER | DT_VCENTER | DT_WORDBREAK | DT_SINGLELINE);
}
}
static void formTopmessageLoadBmp(void)
{
printf("[%s]\n", __FUNCTION__);
bmpsLoad(bmp_load);
my_button->bmpsLoad(ctrls_button,BMP_LOCAL_PATH);
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
if (ctrls_button[i].idc == IDC_BUTTON_COMFIRM) {
ctrls_button[i].color_nor = 0x10B7F5;
}
createMyButton(hDlg,&ctrls_button[i]);
}
}
/* ----------------------------------------------------------------*/
/**
* @brief formTopmessageProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ----------------------------------------------------------------*/
static int formTopmessageProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
switch(message) // 自定义消息
{
case MSG_PAINT:
hdc = BeginPaint (hDlg);
paint(hDlg,hdc);
EndPaint (hDlg, hdc);
return 0;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormTopmessage(HWND hMainWnd,char *title,char *content,void (*fConfirm)(void),void (*fCancel)(void))
{
HWND Form = Screen.Find(form_base_priv.name);
if (title)
strcpy(txt_title,title);
if (content)
strcpy(txt_content,content);
callbackConfirm = fConfirm;
callbackCancel = fCancel;
if(Form) {
ShowWindow(Form,SW_SHOWNORMAL);
} else {
formTopmessageLoadBmp();
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
void topMsgDoorbell(void)
{
createFormTopmessage(0,"提示","有人在按门铃",NULL,NULL);
}
void topMsgCammerError(void)
{
createFormTopmessage(0,"提示","摄像头异常",NULL,NULL);
}
int topMsgFactory(HWND hMainWnd,void (*callback)(void))
{
createFormTopmessage(0,"恢复出厂","恢复出厂将删除所有记录和文件,且不可恢复,是否确认?",configFactory,NULL);
}
static void sleepCallback(void)
{
createFormPowerOffSleep();
protocol_hardcloud->enableSleepMpde();
}
int topMsgSleep(HWND hMainWnd,void (*callback)(void))
{
createFormTopmessage(0,"休眠","是否确认休眠设备?",sleepCallback,NULL);
}
static void rebootCallback(void)
{
createFormPowerOffReboot();
reboot();
}
int topMsgReboot(HWND hMainWnd,void (*callback)(void))
{
createFormTopmessage(0,"重启","是否确认重启设备?",rebootCallback,NULL);
}
static void powerOffCallback(void)
{
protocol_singlechip->cmdPowerOff();
formVideoLayerGotoPoweroff();
}
int topMsgShutdown(HWND hMainWnd,void (*callback)(void))
{
createFormTopmessage(0,"关机","是否确认关机设备?请确认未在充电状态后关机",powerOffCallback,NULL);
}
<file_sep>/src/gui/form_monitor.c
/*
* =============================================================================
*
* Filename: form_monitor.c
*
* Description: 设置界面
*
* Version: 1.0
* Created: 2018-03-01 23:32:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <string.h>
#include "externfunc.h"
#include "screen.h"
#include "my_button.h"
#include "my_title.h"
#include "sql_handle.h"
#include "protocol.h"
#include "my_video.h"
#include "form_video.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formMonitorProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void buttonExitPress(HWND hwnd, int id, int nc, DWORD add_data);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_SET_LOCAL > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define BMP_LOCAL_PATH "main/"
enum {
IDC_TIMER_1S = IDC_FORM_MONITOR_STATR,
IDC_BUTTON_EXIT,
IDC_ICONVIEW,
IDC_LB_REMINDER,
IDC_TITLE,
};
struct IconviewItem {
char user_id[32];
char nick_name[128];
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static HWND hIconView;
static BITMAP bmp_access_nor; // 背景
static BITMAP bmp_access_pre; // 背景
static int bmp_load_finished = 0;
static int flag_timer_stop = 0;
static struct IconviewItem item_data[16];
static BmpLocation bmp_load[] = {
{&bmp_access_pre,BMP_LOCAL_PATH"ico_监视门口机_pre.png"},
{&bmp_access_nor,BMP_LOCAL_PATH"ico_监视门口机_nor.png"},
{NULL},
};
static MY_CTRLDATA ChildCtrls [] = {
ICONVIEW(192,200,640,304,IDC_ICONVIEW),
STATIC_LB(192,350,640,100,IDC_LB_REMINDER,"正在获取数据...",&font22,0x0),
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
// WS_EX_AUTOSECONDARYDC,
WS_EX_NONE,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "Fmonitor",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formMonitorProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
};
static MyCtrlButton ctrls_button[] = {
{IDC_BUTTON_EXIT,MYBUTTON_TYPE_ONE_STATE|MYBUTTON_TYPE_TEXT_NULL,"关闭",974,20,buttonExitPress},
{0},
};
static MyCtrlTitle ctrls_title[] = {
{0},
};
static FormBase* form_base = NULL;
static void enableAutoClose(void)
{
Screen.setCurrent(form_base_priv.name);
flag_timer_stop = 0;
}
/* ----------------------------------------------------------------*/
/**
* @brief buttonExitPress 退出按钮
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ----------------------------------------------------------------*/
static void buttonExitPress(HWND hwnd, int id, int nc, DWORD add_data)
{
ShowWindow(GetParent(hwnd),SW_HIDE);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief paint 固定表头绘制函数
*
* @param hWnd
* @param hdc
*/
/* ---------------------------------------------------------------------------*/
static void paint (HWND hWnd, HDC hdc)
{
RECT rc_text;
SetBrushColor (hdc,PIXEL_lightwhite);
rc_text.left = 192;
rc_text.right = 832;
rc_text.top = 148;
rc_text.bottom = 200;
FillBox (hdc, rc_text.left,rc_text.top,RECTW(rc_text),RECTH(rc_text));
RECT rcDraw;
SetBkMode (hdc, BM_TRANSPARENT);
SetTextColor (hdc, 0x10B7F5);
SelectFont (hdc, font20);
rcDraw.left = 206;
rcDraw.top = 159;
TextOut (hdc, rcDraw.left, rcDraw.top, "监视门口机");
SetPenColor (hdc, 0xDDDDDD);
MoveTo (hdc, 192,199); LineTo (hdc, 832,199);
// MoveTo (hdc, 192,325); LineTo (hdc, 832,325);
// MoveTo (hdc, 318,199); LineTo (hdc, 318,492);
// MoveTo (hdc, 447,199); LineTo (hdc, 447,492);
// MoveTo (hdc, 576,199); LineTo (hdc, 576,492);
// MoveTo (hdc, 705,199); LineTo (hdc, 705,492);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myDrawItem 列表自定义绘图函数
*
* @param hWnd
* @param hsvi
* @param hdc
* @param rcDraw
*/
/* ---------------------------------------------------------------------------*/
static void myDrawItem (HWND hWnd, GHANDLE hsvi, HDC hdc, RECT *rcDraw)
{
#define FILL_BMP_STRUCT(left,top,img) \
FillBoxWithBitmap(hdc,left, top,img.bmWidth,img.bmHeight,&img)
const char *label = (const char*)iconview_get_item_label (hsvi);
SetBkMode (hdc, BM_TRANSPARENT);
SelectFont (hdc, font20);
int bmp_x = rcDraw->left + 45;//rcDraw->left + (rcDraw->right - rcDraw->left - bmp_access_pre.bmWidth) / 2;
int bmp_y = rcDraw->top + 26;//rcDraw->top + (rcDraw->bottom - rcDraw->top - bmp_access_pre.bmHeight) / 2;
if (iconview_is_item_hilight(hWnd, hsvi)) {
SetTextColor (hdc, 0x10B7F5);
FILL_BMP_STRUCT(bmp_x,bmp_y,bmp_access_pre);
} else {
SetTextColor (hdc, 0x999999);
FILL_BMP_STRUCT(bmp_x,bmp_y,bmp_access_nor);
}
if (label) {
RECT rcTxt = *rcDraw;
rcTxt.top = rcDraw->top + 77 ;//rcTxt.bottom - GetWindowFont (hWnd)->size * 2;
// rcTxt.left = rcTxt.left - (GetWindowFont (hWnd)->size) + 2;
DrawText (hdc, label, -1, &rcTxt, DT_CENTER | DT_VCENTER);
}
}
static void iconviewNotify(HWND hwnd, int id, int nc, DWORD add_data)
{
int idx = SendMessage (hIconView, SVM_GETCURSEL, 0, 0);
char *user_id;
user_id = (char *)SendMessage (hIconView, SVM_GETITEMADDDATA, idx, 0);
if (user_id) {
ShowWindow(hwnd,SW_HIDE);
createFormVideo(0,FORM_VIDEO_TYPE_MONITOR,NULL,0);
my_video->videoCallOut(user_id);
}
}
static void iconviewAddItem(int count,char *name,char *user_id)
{
IVITEMINFO ivii;
memset (&ivii, 0, sizeof(IVITEMINFO));
ivii.bmp = &bmp_access_nor;
ivii.nItem = count;
ivii.label = name;
ivii.addData = (DWORD)user_id;
SendMessage (hIconView, IVM_ADDITEM, 0, (LPARAM)&ivii);
}
void formMonitorLoadBmp(void)
{
if (bmp_load_finished == 1)
return;
printf("[%s]\n", __FUNCTION__);
bmpsLoad(bmp_load);
my_button->bmpsLoad(ctrls_button,BMP_LOCAL_PATH);
bmp_load_finished = 1;
}
static void loadIconviewData(void)
{
int i;
memset(item_data,0,sizeof(struct IconviewItem));
int user_num = sqlGetUserInfoUseScopeStart(DEV_TYPE_ENTRANCEMACHINE);
SendMessage (hIconView, IVM_RESETCONTENT, 0, 0);
if (user_num == -1) {
ShowWindow(GetDlgItem(form_base->hDlg,IDC_LB_REMINDER),SW_SHOWNORMAL);
return;
}
ShowWindow(GetDlgItem(form_base->hDlg,IDC_LB_REMINDER),SW_HIDE);
for (i=0; i<user_num && i<16; i++) {
sqlGetUserInfosUseScope(item_data[i].user_id,item_data[i].nick_name);
iconviewAddItem(i,item_data[i].nick_name,item_data[i].user_id);
}
sqlGetUserInfoEnd();
user_num += sqlGetUserInfoUseScopeStart(DEV_TYPE_HOUSEENTRANCEMACHINE);
for (; i<user_num && i<16; i++) {
sqlGetUserInfosUseScope(item_data[i].user_id,item_data[i].nick_name);
iconviewAddItem(i,item_data[i].nick_name,item_data[i].user_id);
}
sqlGetUserInfoEnd();
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_title[i].idc != 0; i++) {
ctrls_title[i].font = font20;
createMyTitle(hDlg,&ctrls_title[i]);
}
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
createMyButton(hDlg,&ctrls_button[i]);
}
hIconView = GetDlgItem (hDlg, IDC_ICONVIEW);
SetWindowBkColor (hIconView, PIXEL_lightwhite);
SendMessage (hIconView, IVM_SETITEMDRAW, 0, (LPARAM)myDrawItem);
SendMessage (hIconView, IVM_SETITEMSIZE, 123, 152);
RECT rcMargin;
memset(&rcMargin,0,sizeof(RECT));
SendMessage (hIconView, IVM_SETMARGINS, 0, (LPARAM)&rcMargin);
loadIconviewData();
}
/* ----------------------------------------------------------------*/
/**
* @brief formMonitorProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ----------------------------------------------------------------*/
static int formMonitorProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
switch(message) // 自定义消息
{
case MSG_TIMER:
{
if (flag_timer_stop)
return 0;
} break;
case MSG_PAINT:
hdc = BeginPaint (hDlg);
paint(hDlg,hdc);
EndPaint (hDlg, hdc);
return 0;
case MSG_COMMAND:
{
int id = LOWORD (wParam);
int code = HIWORD (wParam);
if (code == SVN_CLICKED)
iconviewNotify(hDlg,id,code,0);
break;
}
case MSG_ERASEBKGND:
{
drawBackground(hDlg,
(HDC)wParam,
(const RECT*)lParam, NULL,0x0);
} return 0;
case MSG_ENABLE_WINDOW:
enableAutoClose();
break;
case MSG_DISABLE_WINDOW:
flag_timer_stop = 1;
break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormMonitor(HWND hMainWnd,void (*callback)(void))
{
HWND Form = Screen.Find(form_base_priv.name);
if(Form) {
Screen.setCurrent(form_base_priv.name);
loadIconviewData();
ShowWindow(Form,SW_SHOWNORMAL);
} else {
if (bmp_load_finished == 0) {
// topMessage(hMainWnd,TOPBOX_ICON_LOADING,NULL );
return 0;
}
form_base_priv.callBack = callback;
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
<file_sep>/src/hal/hal_watchdog.c
/*
* =============================================================================
*
* Filename: hal_watchdog.c
*
* Description: 硬件层 看门狗接口
*
* Version: 1.0
* Created: 2018-12-12 15:51:59
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <linux/watchdog.h>
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static int fd = 0;
void halWatchDogOpen(void)
{
#ifndef WATCHDOG_DEBUG
if(fd > 0) {
return;
}
fd = open("/dev/watchdog", O_WRONLY);
if (fd == -1) {
perror("watchdog");
} else {
printf("Init WatchDog!!!!!!!!!!!!!!!!!!\n");
}
#endif
}
void halWatchDogFeed(void)
{
#ifndef WATCHDOG_DEBUG
if(fd <= 0) {
return;
}
ioctl(fd, WDIOC_KEEPALIVE);
#endif
}
void halWatchDogClose(void)
{
#ifndef WATCHDOG_DEBUG
if(fd <= 0) {
return;
}
char * closestr="V";
write(fd,closestr,strlen(closestr));
close(fd);
fd = -2;
#endif
}
<file_sep>/src/gui/form_setting_timer.c
/*
* =============================================================================
*
* Filename: form_setting_timer.c
*
* Description: 时间设置界面
*
* Version: 1.0
* Created: 2018-03-01 23:32:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include "externfunc.h"
#include "screen.h"
#include "config.h"
#include "my_ntp.h"
#include "my_button.h"
#include "my_scroll.h"
#include "my_title.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
extern int createFormSettingDate(HWND hMainWnd,void (*callback)(void));
extern int createFormSettingTimeReal(HWND hMainWnd,void (*callback)(void));
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formSettingTimerProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void buttonTitleNotify(HWND hwnd, int id, int nc, DWORD add_data);
static int buttonSwitchNotify(HWND hwnd,void (*callback)(void));
static void reloadTimer(void);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_SET_LOCAL > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define BMP_LOCAL_PATH "setting/"
enum {
IDC_TIMER_1S = IDC_FORM_SETTING_TIEMR,
IDC_BUTTON_SWITCH,
IDC_SCROLLVIEW,
IDC_TITLE,
};
struct ScrollviewItem {
char title[32]; // 左边标题
char text[32]; // 右边文字
int (*callback)(HWND,void (*callback)(void)); // 点击回调函数
int index; // 元素位置
int item_type; // 0标准 1开关
int switch_state; // 当item_type为1时,此变量有效,0关闭,1开启
int text_color_type; // 文字颜色,0暗,1亮
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static BITMAP bmp_enter; // 进入
static BITMAP image_swich_off;// 关闭状态图片
static BITMAP image_swich_on; // 打开状态图片
static HWND hScrollView;
static int bmp_load_finished = 0;
static int flag_timer_stop = 0;
static struct ScrollviewItem locoal_list[] = {
{"自动获取","",buttonSwitchNotify},
{"设置日期","",createFormSettingDate},
{"设置时间","",createFormSettingTimeReal},
{0},
};
static BmpLocation bmp_load[] = {
{&bmp_enter, BMP_LOCAL_PATH"ico_返回_1.png"},
{&image_swich_off,BMP_LOCAL_PATH"Switch Off_小.png"},
{&image_swich_on, BMP_LOCAL_PATH"Switch On_小.png"},
{NULL},
};
static MY_CTRLDATA ChildCtrls [] = {
SCROLLVIEW(0,40,1024,580,IDC_SCROLLVIEW),
};
static MyCtrlButton ctrls_button[] = {
{0},
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
// WS_EX_AUTOSECONDARYDC,
WS_EX_NONE,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "FsetTimer",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formSettingTimerProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
.auto_close_time_set = 30,
};
static MyCtrlTitle ctrls_title[] = {
{
IDC_TITLE,
MYTITLE_LEFT_EXIT,
MYTITLE_RIGHT_NULL,
0,0,1024,40,
"日期时间",
"",
0xffffff, 0x333333FF,
buttonTitleNotify,
},
{0},
};
static FormBase* form_base = NULL;
static void enableAutoClose(void)
{
reloadTimer();
Screen.setCurrent(form_base_priv.name);
flag_timer_stop = 0;
}
static void reloadTimer(void)
{
int i;
SVITEMINFO svii;
struct ScrollviewItem *plist = locoal_list;
SendMessage (hScrollView, SVM_RESETCONTENT, 0, 0);
struct tm *tm = getTime();
for (i=0; plist->title[0] != 0; i++) {
plist->index = i;
plist->item_type = 0;
plist->text_color_type = 1;
svii.nItemHeight = 60;
svii.addData = (DWORD)plist;
svii.nItem = i;
if (strcmp("设置日期",plist->title) == 0) {
sprintf(plist->text,"%d年%d月%d日",tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday);
if (g_config.auto_sync_time)
plist->text_color_type = 0;
} else if (strcmp("设置时间",plist->title) == 0) {
sprintf(plist->text,"%d:%02d",tm->tm_hour,tm->tm_min);
if (g_config.auto_sync_time)
plist->text_color_type = 0;
} else if (strcmp("自动获取",plist->title) == 0) {
plist->item_type = 1;
plist->switch_state = g_config.auto_sync_time;
}
SendMessage (hScrollView, SVM_ADDITEM, 0, (LPARAM)&svii);
SendMessage (hScrollView, SVM_SETITEMADDDATA, i, (DWORD)plist);
plist++;
}
}
/* ----------------------------------------------------------------*/
/**
* @brief buttonTitleNotify 标题按钮
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ----------------------------------------------------------------*/
static void buttonTitleNotify(HWND hwnd, int id, int nc, DWORD add_data)
{
ShowWindow(GetParent(hwnd),SW_HIDE);
}
static int buttonSwitchNotify(HWND hwnd,void (*callback)(void))
{
g_config.auto_sync_time = hwnd;
ntpEnable(g_config.auto_sync_time);
ConfigSavePublic();
reloadTimer();
}
void formSettingTimerLoadBmp(void)
{
if (bmp_load_finished == 1)
return;
printf("[%s]\n", __FUNCTION__);
bmpsLoad(bmp_load);
bmp_load_finished = 1;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief scrollviewNotify
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ---------------------------------------------------------------------------*/
static void scrollviewNotify(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != SVN_CLICKED)
return;
int idx = SendMessage (hScrollView, SVM_GETCURSEL, 0, 0);
struct ScrollviewItem *plist;
plist = (struct ScrollviewItem *)SendMessage (hScrollView, SVM_GETITEMADDDATA, idx, 0);
if (!plist)
return;
if (!plist->callback)
return;
if (plist->item_type == 0 && g_config.auto_sync_time == 0) {
flag_timer_stop = 1;
plist->callback(hwnd,enableAutoClose);
} else if (plist->item_type == 1){
plist->switch_state ^= 1;
plist->callback(plist->switch_state,NULL);
InvalidateRect (hwnd, NULL, TRUE);
}
}
static void myDrawItem (HWND hWnd, HSVITEM hsvi, HDC hdc, RECT *rcDraw)
{
#define FILL_BMP_STRUCT(left,top,img) \
FillBoxWithBitmap(hdc,left, top,img.bmWidth,img.bmHeight,&img)
#define DRAW_TABLE(rc,offset,color) \
do { \
SetPenColor (hdc, color); \
if (p_item->index) { \
MoveTo (hdc, rc->left + offset, rc->top); \
LineTo (hdc, rc->right,rc->top); \
} \
MoveTo (hdc, rc->left + offset, rc->bottom); \
LineTo (hdc, rc->right,rc->bottom); \
} while (0)
struct ScrollviewItem *p_item = (struct ScrollviewItem *)scrollview_get_item_adddata (hsvi);
SetBkMode (hdc, BM_TRANSPARENT);
SetTextColor (hdc, PIXEL_lightwhite);
SelectFont (hdc, font20);
if (p_item->callback && p_item->item_type == 0)
FILL_BMP_STRUCT(rcDraw->left + 968,rcDraw->top + 15,bmp_enter);
if (p_item->item_type == 1) {
if (p_item->switch_state)
FILL_BMP_STRUCT(rcDraw->left + 968,rcDraw->top + 15,image_swich_on);
else
FILL_BMP_STRUCT(rcDraw->left + 968,rcDraw->top + 15,image_swich_off);
}
// 绘制表格
DRAW_TABLE(rcDraw,0,0xCCCCCC);
if (p_item->text_color_type)
SetTextColor (hdc, RGBA2Pixel (hdc, 0xCC, 0xCC, 0xCC, 0xFF));
else
SetTextColor (hdc, RGBA2Pixel (hdc, 0x99, 0x99, 0x99, 0xFF));
// 输出文字
TextOut (hdc, rcDraw->left + 30, rcDraw->top + 15, p_item->title);
RECT rc;
memcpy(&rc,rcDraw,sizeof(RECT));
rc.left += 512;
rc.right -= 70;
DrawText (hdc,p_item->text, -1, &rc,
DT_VCENTER | DT_RIGHT | DT_WORDBREAK | DT_SINGLELINE);
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_title[i].idc != 0; i++) {
ctrls_title[i].font = font20;
createMyTitle(hDlg,&ctrls_title[i]);
}
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
createMyButton(hDlg,&ctrls_button[i]);
}
hScrollView = GetDlgItem (hDlg, IDC_SCROLLVIEW);
SendMessage (hScrollView, SVM_SETITEMDRAW, 0, (LPARAM)myDrawItem);
reloadTimer();
}
/* ----------------------------------------------------------------*/
/**
* @brief formSettingTimerProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ----------------------------------------------------------------*/
static int formSettingTimerProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
switch(message) // 自定义消息
{
case MSG_TIMER:
{
if (flag_timer_stop)
return 0;
} break;
case MSG_COMMAND:
{
int id = LOWORD (wParam);
int code = HIWORD (wParam);
scrollviewNotify(hDlg,id,code,0);
break;
}
case MSG_ENABLE_WINDOW:
enableAutoClose();
break;
case MSG_DISABLE_WINDOW:
flag_timer_stop = 1;
break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormSettingTimer(HWND hMainWnd,void (*callback)(void))
{
HWND Form = Screen.Find(form_base_priv.name);
if(Form) {
Screen.setCurrent(form_base_priv.name);
reloadTimer();
ShowWindow(Form,SW_SHOWNORMAL);
} else {
if (bmp_load_finished == 0) {
return 0;
}
form_base_priv.callBack = callback;
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
<file_sep>/src/gui/my_controls/my_controls.h
/*
* =============================================================================
*
* Filename: my_controls.h
*
* Description: 自定义控件接口
*
* Version: 1.0
* Created: 2019-04-24 08:26:08
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_CONTROLS_H
#define _MY_CONTROLS_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <minigui/common.h>
#include <minigui/minigui.h>
#include <minigui/gdi.h>
#include <minigui/window.h>
#include <minigui/control.h>
typedef struct _MyControls {
BOOL (*regist)(void);
void (*unregist)(void);
void (*bmpsLoad)(void *ctrl,char *path);
void (*bmpsRelease)(void *ctrl);
}MyControls;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/drivers/ipc_server.h
/*
* =============================================================================
*
* Filename: ipc_server.h
*
* Description: 进程通讯接口
*
* Version: virsion
* Created: 2019-07-26 11:18:51
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _IPC_SERVER_H
#define _IPC_SERVER_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef void (*IpcCallback)(char *data,int size);
struct _IpcServerPriv;
typedef struct _IpcServer{
struct _IpcServerPriv *priv;
int (*sendData)(struct _IpcServer *,const char *path,void *data,int size);
}IpcServer;
void waitIpcOpen(const char *path);
IpcServer* ipcCreate(const char *path,IpcCallback func);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/hal/CMakeLists.txt
# 查找当前目录下的所有源文件 并将名称保存到 SRCS_HAL 变量
aux_source_directory(. SRCS_HAL)
STRING( REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER_HAL ${CMAKE_CURRENT_SOURCE_DIR})
set(SUB_DIRS_APP ${SUB_DIRS_APP} hal_mixer )
foreach(sub ${SUB_DIRS_APP})
add_subdirectory(${sub})
endforeach()
# 生成链接库
add_library (${CURRENT_FOLDER_HAL} ${SRCS_HAL})
target_link_libraries (${CURRENT_FOLDER_HAL} ${SUB_DIRS_APP})
<file_sep>/src/app/my_echo.c
/************************************************************************************
文件名称:
文件功能:
函数列表:
修改日期:
*************************************************************************************/
/*------------------------------------------- 头文件包含 ------------------------------------------*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "my_echo.h"
#include "RK_VOICE_ProInterface.h"
void RK_VOICE_SetPara(short int *pshwPara, short int shwLen)
{
short int shwCnt;
for (shwCnt=0; shwCnt<shwLen; shwCnt++)
{
pshwPara[shwCnt] = 0;
}
#if 1
/*------ 0.总模块参数设置 ------*/
pshwPara[0] = 16000; /* INT16 Q0 采样率设置;当前仅支持8000,16000 */
pshwPara[1] = 320; /* INT16 Q0 处理帧长设置;8k:160;16k:320 */
/*------ 1.AEC 参数设置 ------*/
pshwPara[10] = 1; /* 使能标志:回声消除使能 */
pshwPara[11] = 320; /* INT16 Q0 处理帧长设置;8k:160;16k:320 */
pshwPara[12] = 1; /* INT16 Q0 默认延时设置(单位样点数),0到3200 */
pshwPara[13] = 0; /* 使能标志:延时估计使能 */
pshwPara[14] = 160; /* INT16 Q0 延时估计处理帧长;8k:80;16k:160 */
pshwPara[15] = 16; /* INT16 Q0 最大delay帧数设置,一帧10ms;当前固定值 */
pshwPara[16] = 0; /* INT16 Q0 反向超前帧数,一帧10ms;当前固定值 0 */
pshwPara[17] = 320; /* INT16 Q0 MDF处理帧长设置;当前固定值 8k:160;16k:320 */
pshwPara[18] = 640; /* INT16 Q0 MDF拖尾长度设置,即滤波长度;当前固定值 8k:320;16k:640 */
pshwPara[19] = 16000; /* INT16 Q0 MDF采样率设置;当前固定值 8k,16k */
pshwPara[20] = 320; /* INT16 Q0 NLP处理帧长设置;当前固定值 8k:160;16k:320 */
pshwPara[21] = 32; /* INT16 Q0 NLP处理子带设置;当前固定值 8k:24;16k:32 */
pshwPara[22] = 1; /* 非线性回声消除COH方法使能标志 */
pshwPara[23] = 1; /* INT16 Q0 COH人工回声增益次方施加 */
pshwPara[24] = 0; /* 非线性回声消除SER方法使能标志 */
pshwPara[25] = 1; /* INT16 Q0 SER人工回声增益次方施加 */
pshwPara[26] = 320; /* INT16 Q0 DTD判决处理帧长;当前固定值 8k:160;16k:320 */
pshwPara[27] = 32; /* INT16 Q0 DTD判决子带个数;当前固定值 8k:24;16k:32 */
pshwPara[28] = 200; /* INT16 Q0 PASS态判断:远端信号幅度阈值 */
pshwPara[29] = 5; /* INT16 Q0 PASS态判断:进入PASS态平滑帧数 */
pshwPara[30] = 10; /* INT16 Q0 子带PASS态判断:子带能量阈值 */
pshwPara[31] = 1; /* 使能标志:子带DTD的0,1判断 */
pshwPara[32] = 10; /* INT16 Q0 远端信号大于该阈值即做子带DTD的0,1判断 */
pshwPara[33] = 20; /* INT16 Q0 残差低于此阈值则做子带DTD的0判断 */
pshwPara[34] = (short int)(0.3f*(1<<15)); /* INT16 Q15 残差与近端能量比低于此阈值则做子带DTD的0判断 */
pshwPara[35] = 1; /* INT16 Q0 残差平滑DTD0,1判断时对非线性程度倍数扩充 1至5 */
pshwPara[36] = 32; /* INT16 Q0 高于该子带号的子带实行高频子带强压制为0 */
pshwPara[37] = 5; /* INT16 Q0 实行高频压制远端能量阈值 */
pshwPara[38] = 1; /* INT16 Q0 DTD整帧判决:使用子带起始索引 1-24 */
pshwPara[39] = 10; /* INT16 Q0 DTD整帧判决:使用子带终止索引 1-24 */
pshwPara[40] = 3; /* INT16 Q0 DTD整帧判决:高于Gain阈值子带数高于该值判DT */
pshwPara[41] = 3; /* INT16 Q0 DTD整帧判决:连续出现该值个数的ST才最终判为ST */
pshwPara[42] = (short int)(0.30f*(1<<15)); /* INT16 Q15 DTD整帧判决:Gain阈值初始值 */
pshwPara[43] = (short int)(0.04f*(1<<15)); /* INT16 Q15 DTD整帧判决:Gain阈值调整步长 */
pshwPara[44] = (short int)(0.40f*(1<<15)); /* INT16 Q15 DTD整帧判决:Gain阈值最大值 */
pshwPara[45] = (short int)(0.25f*(1<<15)); /* INT16 Q15 DTD整帧判决:Gain阈值最小值 */
pshwPara[46] = (short int)(0.0313f*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号0 */
pshwPara[47] = (short int)(0.0625*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号1 */
pshwPara[48] = (short int)(0.0938*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号2 */
pshwPara[49] = (short int)(0.1250*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号3 */
pshwPara[50] = (short int)(0.1563*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号4 */
pshwPara[51] = (short int)(0.1875*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号5 */
pshwPara[52] = (short int)(0.2188*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号6 */
pshwPara[53] = (short int)(0.2500*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号7 */
pshwPara[54] = (short int)(0.2813*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号8 */
pshwPara[55] = (short int)(0.3125*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号9 */
pshwPara[56] = (short int)(0.3438*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号10 */
pshwPara[57] = (short int)(0.3750*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号11 */
pshwPara[58] = (short int)(0.4063*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号12 */
pshwPara[59] = (short int)(0.4375*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号13 */
pshwPara[60] = (short int)(0.4688*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号14 */
pshwPara[61] = (short int)(0.5000*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号15 */
pshwPara[62] = (short int)(0.5313*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号16 */
pshwPara[63] = (short int)(0.5625*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号17 */
pshwPara[64] = (short int)(0.5938*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号18 */
pshwPara[65] = (short int)(0.6250*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号19 */
pshwPara[66] = (short int)(0.6563*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号20 */
pshwPara[67] = (short int)(0.6875*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号21 */
pshwPara[68] = (short int)(0.7188*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号22 */
pshwPara[69] = (short int)(0.7500*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号23 */
pshwPara[70] = (short int)(0.7813*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号24 */
pshwPara[71] = (short int)(0.8125*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号25 */
pshwPara[72] = (short int)(0.8438*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号26 */
pshwPara[73] = (short int)(0.8750*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号27 */
pshwPara[74] = (short int)(0.9063*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号28 */
pshwPara[75] = (short int)(0.9375*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号29 */
pshwPara[76] = (short int)(0.9688*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号30 */
pshwPara[77] = (short int)(1.0000*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号31 */
/*------ 2.ANR 参数设置 ------*/
pshwPara[90] = 1; /* 使能标志:上行噪声抑制使能 */
pshwPara[91] = 16000; /* INT16 Q0 ANR采样率设置,当前固定值 8k,16k */
pshwPara[92] = 320; /* INT16 Q0 ANR帧长设置,当前固定值 8k:160;16k:320 */
pshwPara[93] = 32; /* INT16 Q0 ANR子带个数,当前固定值 8k:24;16k:32 */
pshwPara[94] = 2; /* INT16 Q0 ANR噪声估计时间片,0到10 */
pshwPara[110] = 1; /* 使能标志:下行噪声抑制使能 */
pshwPara[111] = 16000; /* INT16 Q0 ANR采样率设置,当前固定值 8k,16k */
pshwPara[112] = 320; /* INT16 Q0 ANR帧长设置,当前固定值 8k:160;16k:320 */
pshwPara[113] = 32; /* INT16 Q0 ANR子带个数,当前固定值 8k:24;16k:32 */
pshwPara[114] = 2; /* INT16 Q0 ANR噪声估计时间片,0到10 */
/*------ 3.AGC 参数配置 ------*/
pshwPara[130] = 1; /* 使能标志:上行AGC消除使能 */
pshwPara[131] = 16000; /* INT16 Q0 采样率配置;当前固定值 8k,16k */
pshwPara[132] = 320; /* INT16 Q0 处理帧长;当前固定值 8k:160;16k:320 */
pshwPara[133] = (short int)(6.0f*(1<<5)); /* INT16 Q5 线性段提升dB数 */
pshwPara[134] = (short int)(-55.0f*(1<<5)); /* INT16 Q5 扩张段起始能量dB阈值 */
pshwPara[135] = (short int)(-46.0f*(1<<5)); /* INT16 Q5 线性段起始能量dB阈值 */
pshwPara[136] = (short int)(-24.0f*(1<<5)); /* INT16 Q5 压缩段起始能量dB阈值 */
pshwPara[137] = (short int)(1.2f*(1<<12)); /* INT16 Q12 扩张段斜率 */
pshwPara[138] = (short int)(0.8f*(1<<12)); /* INT16 Q12 线性段斜率 */
pshwPara[139] = (short int)(0.4f*(1<<12)); /* INT16 Q12 压缩段斜率 */
pshwPara[140] = 40; /* INT16 Q0 扩张段时域平滑点数 */
pshwPara[141] = 80; /* INT16 Q0 线性段时域平滑点数 */
pshwPara[142] = 80; /* INT16 Q0 压缩段时域平滑点数 */
pshwPara[150] = 0; /* 使能标志:上行AGC消除使能 */
pshwPara[151] = 16000; /* INT16 Q0 采样率配置;当前固定值 8k,16k */
pshwPara[152] = 320; /* INT16 Q0 处理帧长;当前固定值 8k:160;16k:320 */
pshwPara[153] = (short int)(6.0f*(1<<5)); /* INT16 Q5 线性段提升dB数 */
pshwPara[154] = (short int)(-55.0f*(1<<5)); /* INT16 Q5 扩张段起始能量dB阈值 */
pshwPara[155] = (short int)(-46.0f*(1<<5)); /* INT16 Q5 线性段起始能量dB阈值 */
pshwPara[156] = (short int)(-24.0f*(1<<5)); /* INT16 Q5 压缩段起始能量dB阈值 */
pshwPara[157] = (short int)(1.2f*(1<<12)); /* INT16 Q12 扩张段斜率 */
pshwPara[158] = (short int)(0.8f*(1<<12)); /* INT16 Q12 线性段斜率 */
pshwPara[159] = (short int)(0.4f*(1<<12)); /* INT16 Q12 压缩段斜率 */
pshwPara[160] = 40; /* INT16 Q0 扩张段时域平滑点数 */
pshwPara[161] = 80; /* INT16 Q0 线性段时域平滑点数 */
pshwPara[162] = 80; /* INT16 Q0 压缩段时域平滑点数 */
/*------ 4.EQ 参数设置 ------*/
pshwPara[170] = 0; /* 使能标志:上行EQ使能标志 */
pshwPara[171] = 320; /* INT16 Q0 上行EQ处理帧长;当前固定值 8k:160;16k:320 */
pshwPara[172] = 1; /* INT16 Q0 上行EQ滤波器长度 */
pshwPara[173] = (short int)(1.0f*(1<<15)); /* INT16 Q15 上行EQ滤波器系数数组 */
pshwPara[330] = 0; /* 使能标志:上行EQ使能标志 */
pshwPara[331] = 320; /* INT16 Q0 上行EQ处理帧长;当前固定值 8k:160;16k:320 */
pshwPara[332] = 1; /* INT16 Q0 上行EQ滤波器长度 */
pshwPara[333] = (short int)(1.0f*(1<<15)); /* INT16 Q15 上行EQ滤波器系数数组 */
/*------ 5.CNG 参数设置 ------*/
pshwPara[490] = 1; /* 使能标志:CNG使能标志 */
pshwPara[491] = 16000; /* INT16 Q0 CNG处理采样率;当前固定值 8k,16k */
pshwPara[492] = 320; /* INT16 Q0 CNG处理帧长;当前固定值 8k:160;16k:320 */
pshwPara[493] = 2; /* INT16 Q0 施加舒适噪声幅度比例 */
pshwPara[494] = 10; /* INT16 Q0 白噪随机数生成幅度 */
pshwPara[495] = (short int)(0.92f*(1<<15)); /* INT16 Q15 施加舒适噪声平滑度 */
pshwPara[496] = (short int)(0.3f*(1<<15)); /* INT16 Q15 施加舒适噪声语音纹理模拟程度 */
#else
/*------ 0.总模块参数设置 ------*/
pshwPara[0] = 8000; /* INT16 Q0 采样率设置;当前仅支持8000,16000 */
pshwPara[1] = 160; /* INT16 Q0 处理帧长设置;8k:160;16k:320 */
/*------ 1.AEC 参数设置 ------*/
pshwPara[10] = 1; /* 使能标志:回声消除使能 */
pshwPara[11] = 160; /* INT16 Q0 处理帧长设置;8k:160;16k:320 */
pshwPara[12] = 1; /* INT16 Q0 默认延时设置(单位样点数),0到3200 */
pshwPara[13] = 0; /* 使能标志:延时估计使能 */
pshwPara[14] = 80; /* INT16 Q0 延时估计处理帧长;8k:80;16k:160 */
pshwPara[15] = 16; /* INT16 Q0 最大delay帧数设置,一帧10ms;当前固定值 */
pshwPara[16] = 0; /* INT16 Q0 反向超前帧数,一帧10ms;当前固定值 0 */
pshwPara[17] = 160; /* INT16 Q0 MDF处理帧长设置;当前固定值 8k:160;16k:320 */
pshwPara[18] = 320; /* INT16 Q0 MDF拖尾长度设置,即滤波长度;当前固定值 8k:320;16k:640 */
pshwPara[19] = 8000; /* INT16 Q0 MDF采样率设置;当前固定值 8k,16k */
pshwPara[20] = 160; /* INT16 Q0 NLP处理帧长设置;当前固定值 8k:160;16k:320 */
pshwPara[21] = 24; /* INT16 Q0 NLP处理子带设置;当前固定值 8k:24;16k:32 */
pshwPara[22] = 1; /* 非线性回声消除COH方法使能标志 */
pshwPara[23] = 1; /* INT16 Q0 COH人工回声增益次方施加 */
pshwPara[24] = 0; /* 非线性回声消除SER方法使能标志 */
pshwPara[25] = 1; /* INT16 Q0 SER人工回声增益次方施加 */
pshwPara[26] = 160; /* INT16 Q0 DTD判决处理帧长;当前固定值 8k:160;16k:320 */
pshwPara[27] = 24; /* INT16 Q0 DTD判决子带个数;当前固定值 8k:24;16k:32 */
pshwPara[28] = 200; /* INT16 Q0 PASS态判断:远端信号幅度阈值 */
pshwPara[29] = 5; /* INT16 Q0 PASS态判断:进入PASS态平滑帧数 */
pshwPara[30] = 20; /* INT16 Q0 子带PASS态判断:子带能量阈值 */
pshwPara[31] = 1; /* 使能标志:子带DTD的0,1判断 */
pshwPara[32] = 0; /* INT16 Q0 远端信号大于该阈值即做子带DTD的0,1判断 */
pshwPara[33] = 50; /* INT16 Q0 残差低于此阈值则做子带DTD的0判断 */
pshwPara[34] = (short int)(0.1f*(1<<15)); /* INT16 Q15 残差与近端能量比低于此阈值则做子带DTD的0判断 */
pshwPara[35] = 1; /* INT16 Q0 残差平滑DTD0,1判断时对非线性程度倍数扩充 1至5 */
pshwPara[36] = 24; /* INT16 Q0 高于该子带号的子带实行高频子带强压制为0 */
pshwPara[37] = 5; /* INT16 Q0 实行高频压制远端能量阈值 */
pshwPara[38] = 1; /* INT16 Q0 DTD整帧判决:使用子带起始索引 1-24 */
pshwPara[39] = 5; /* INT16 Q0 DTD整帧判决:使用子带终止索引 1-24 */
pshwPara[40] = 1; /* INT16 Q0 DTD整帧判决:高于Gain阈值子带数高于该值判DT */
pshwPara[41] = 3; /* INT16 Q0 DTD整帧判决:连续出现该值个数的ST才最终判为ST */
pshwPara[42] = (short int)(0.05f*(1<<15)); /* INT16 Q15 DTD整帧判决:Gain阈值初始值 */
pshwPara[43] = (short int)(0.05f*(1<<15)); /* INT16 Q15 DTD整帧判决:Gain阈值调整步长 */
pshwPara[44] = (short int)(0.05f*(1<<15)); /* INT16 Q15 DTD整帧判决:Gain阈值最大值 */
pshwPara[45] = (short int)(0.05f*(1<<15)); /* INT16 Q15 DTD整帧判决:Gain阈值最小值 */
pshwPara[46] = (short int)(0.0417*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号0 */
pshwPara[47] = (short int)(0.0833*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号1 */
pshwPara[48] = (short int)(0.1250*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号2 */
pshwPara[49] = (short int)(0.1667*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号3 */
pshwPara[50] = (short int)(0.2083*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号4 */
pshwPara[51] = (short int)(0.2500*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号5 */
pshwPara[52] = (short int)(0.2917*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号6 */
pshwPara[53] = (short int)(0.3333*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号7 */
pshwPara[54] = (short int)(0.3750*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号8 */
pshwPara[55] = (short int)(0.4167*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号9 */
pshwPara[56] = (short int)(0.4583*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号10 */
pshwPara[57] = (short int)(0.5000*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号11 */
pshwPara[58] = (short int)(0.5417*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号12 */
pshwPara[59] = (short int)(0.5833*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号13 */
pshwPara[60] = (short int)(0.6250*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号14 */
pshwPara[61] = (short int)(0.6667*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号15 */
pshwPara[62] = (short int)(0.7083*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号16 */
pshwPara[63] = (short int)(0.7500*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号17 */
pshwPara[64] = (short int)(0.7917*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号18 */
pshwPara[65] = (short int)(0.8333*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号19 */
pshwPara[66] = (short int)(0.8750*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号20 */
pshwPara[67] = (short int)(0.9167*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号21 */
pshwPara[68] = (short int)(0.9583*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号22 */
pshwPara[69] = (short int)(1.0000*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号23 */
pshwPara[70] = (short int)(1.0000*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号24 */
pshwPara[71] = (short int)(1.0000*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号25 */
pshwPara[72] = (short int)(1.0000*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号26 */
pshwPara[73] = (short int)(1.0000*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号27 */
pshwPara[74] = (short int)(1.0000*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号28 */
pshwPara[75] = (short int)(1.0000*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号29 */
pshwPara[76] = (short int)(1.0000*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号30 */
pshwPara[77] = (short int)(1.0000*(1<<15)); /* INT16 Q15 子带非线性程度配置,子带号31 */
/*------ 2.ANR 参数设置 ------*/
pshwPara[90] = 1; /* 使能标志:上行噪声抑制使能 */
pshwPara[91] = 8000; /* INT16 Q0 ANR采样率设置,当前固定值 8k,16k */
pshwPara[92] = 160; /* INT16 Q0 ANR帧长设置,当前固定值 8k:160;16k:320 */
pshwPara[93] = 24; /* INT16 Q0 ANR子带个数,当前固定值 8k:24;16k:32 */
pshwPara[94] = 5; /* INT16 Q0 ANR噪声估计时间片,0到10 */
pshwPara[110] = 0; /* 使能标志:下行噪声抑制使能 */
pshwPara[111] = 8000; /* INT16 Q0 ANR采样率设置,当前固定值 8k,16k */
pshwPara[112] = 160; /* INT16 Q0 ANR帧长设置,当前固定值 8k:160;16k:320 */
pshwPara[113] = 24; /* INT16 Q0 ANR子带个数,当前固定值 8k:24;16k:32 */
pshwPara[114] = 5; /* INT16 Q0 ANR噪声估计时间片,0到10 */
/*------ 3.AGC 参数配置 ------*/
pshwPara[130] = 1; /* 使能标志:上行AGC消除使能 */
pshwPara[131] = 8000; /* INT16 Q0 采样率配置;当前固定值 8k,16k */
pshwPara[132] = 160; /* INT16 Q0 处理帧长;当前固定值 8k:160;16k:320 */
pshwPara[133] = (short int)(6.0f*(1<<5)); /* INT16 Q5 线性段提升dB数 */
pshwPara[134] = (short int)(-55.0f*(1<<5)); /* INT16 Q5 扩张段起始能量dB阈值 */
pshwPara[135] = (short int)(-46.0f*(1<<5)); /* INT16 Q5 线性段起始能量dB阈值 */
pshwPara[136] = (short int)(-24.0f*(1<<5)); /* INT16 Q5 压缩段起始能量dB阈值 */
pshwPara[137] = (short int)(1.2f*(1<<12)); /* INT16 Q12 扩张段斜率 */
pshwPara[138] = (short int)(0.8f*(1<<12)); /* INT16 Q12 线性段斜率 */
pshwPara[139] = (short int)(0.4f*(1<<12)); /* INT16 Q12 压缩段斜率 */
pshwPara[140] = 20; /* INT16 Q0 扩张段时域平滑点数 */
pshwPara[141] = 40; /* INT16 Q0 线性段时域平滑点数 */
pshwPara[142] = 40; /* INT16 Q0 压缩段时域平滑点数 */
pshwPara[150] = 0; /* 使能标志:上行AGC消除使能 */
pshwPara[151] = 8000; /* INT16 Q0 采样率配置;当前固定值 8k,16k */
pshwPara[152] = 160; /* INT16 Q0 处理帧长;当前固定值 8k:160;16k:320 */
pshwPara[153] = (short int)(6.0f*(1<<5)); /* INT16 Q5 线性段提升dB数 */
pshwPara[154] = (short int)(-55.0f*(1<<5)); /* INT16 Q5 扩张段起始能量dB阈值 */
pshwPara[155] = (short int)(-46.0f*(1<<5)); /* INT16 Q5 线性段起始能量dB阈值 */
pshwPara[156] = (short int)(-24.0f*(1<<5)); /* INT16 Q5 压缩段起始能量dB阈值 */
pshwPara[157] = (short int)(1.2f*(1<<12)); /* INT16 Q12 扩张段斜率 */
pshwPara[158] = (short int)(0.8f*(1<<12)); /* INT16 Q12 线性段斜率 */
pshwPara[159] = (short int)(0.2f*(1<<12)); /* INT16 Q12 压缩段斜率 */
pshwPara[160] = 20; /* INT16 Q0 扩张段时域平滑点数 */
pshwPara[161] = 40; /* INT16 Q0 线性段时域平滑点数 */
pshwPara[162] = 40; /* INT16 Q0 压缩段时域平滑点数 */
/*------ 4.EQ 参数设置 ------*/
pshwPara[170] = 0; /* 使能标志:上行EQ使能标志 */
pshwPara[171] = 160; /* INT16 Q0 上行EQ处理帧长;当前固定值 8k:160;16k:320 */
pshwPara[172] = 1; /* INT16 Q0 上行EQ滤波器长度 */
pshwPara[173] = (short int)(1.0f*(1<<15)); /* INT16 Q15 上行EQ滤波器系数数组 */
pshwPara[330] = 0; /* 使能标志:上行EQ使能标志 */
pshwPara[331] = 160; /* INT16 Q0 上行EQ处理帧长;当前固定值 8k:160;16k:320 */
pshwPara[332] = 1; /* INT16 Q0 上行EQ滤波器长度 */
pshwPara[333] = (short int)(1.0f*(1<<15)); /* INT16 Q15 上行EQ滤波器系数数组 */
/*------ 5.CNG 参数设置 ------*/
pshwPara[490] = 1; /* 使能标志:CNG使能标志 */
pshwPara[491] = 8000; /* INT16 Q0 CNG处理采样率;当前固定值 8k,16k */
pshwPara[492] = 160; /* INT16 Q0 CNG处理帧长;当前固定值 8k:160;16k:320 */
pshwPara[493] = 2; /* INT16 Q0 施加舒适噪声幅度比例 */
pshwPara[494] = 10; /* INT16 Q0 白噪随机数生成幅度 */
pshwPara[495] = (short int)(0.92f*(1<<15)); /* INT16 Q15 施加舒适噪声平滑度 */
pshwPara[496] = (short int)(0.3f*(1<<15)); /* INT16 Q15 施加舒适噪声语音纹理模拟程度 */
#endif
}
void rkEchoInit(void)
{
short int ashwPara[500] = {0};
RK_VOICE_SetPara(ashwPara, 500);
/* 初始化 */
// VOICE_Init(ashwPara);
}
void rkEchoUnInit(void)
{
// VOICE_Destory();
}
void rkEchoTx(short int *pshwIn,
short int *pshwRef,
short int *pshwOut,
int swFrmLen)
{
// VOICE_ProcessTx(pshwIn, pshwRef, pshwOut, swFrmLen);
}
void rkEchoRx(short int *pshwIn,
short int *pshwOut,
int swFrmLen)
{
// VOICE_ProcessRx(pshwIn, pshwOut, swFrmLen);
}
int test()
{
// int swCnt, swFrmLen;
// int swFrmNum;
// FILE *fp_in = fopen("../test/TEST_ALL_Case1/in_411.pcm", "rb");
// FILE *fp_rx = fopen("../test/TEST_ALL_Case1/ref_411.pcm", "rb");
// FILE *fp_out = fopen("../test/TEST_ALL_Case1/rk_411_out_31.pcm", "wb");
// short int ashwTxIn[320] = {0};
// short int ashwTxOut[320] = {0};
// short int ashwRxIn[320] = {0};
// short int ashwRxOut[320] = {0};
// short int ashwPara[500] = {0};
// RK_VOICE_SetPara(ashwPara, 500);
// [> 初始化 <]
// VOICE_Init(ashwPara);
// swFrmNum = 0;
// swFrmLen = 320;
// [> 2.主体功能函数测试<]
// while (!feof(fp_in) && !feof(fp_rx))
// {
// fread(ashwTxIn, sizeof(short), swFrmLen, fp_in);
// fread(ashwRxIn, sizeof(short), swFrmLen, fp_rx);
// swFrmNum++;
// if (16 == swFrmNum)
// {
// swFrmNum = swFrmNum;
// }
// [> 调用单帧处理函数 <]
// VOICE_ProcessRx(ashwRxIn, ashwRxOut, swFrmLen);
// VOICE_ProcessTx(ashwTxIn, ashwRxIn, ashwTxOut, swFrmLen);
// fwrite(ashwTxOut, sizeof(short), swFrmLen, fp_out);
// }
// [> 3.测试环境清理 <]
// VOICE_Destory();
// fclose(fp_in);
// fclose(fp_rx);
// fclose(fp_out);
}
<file_sep>/src/main.c
/*
* =============================================================================
*
* Filename: main.c
*
* Description: 智能猫眼
*
* Version: 1.0
* Created: 2019-04-19 16:47:01
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include "debug.h"
#include "my_gpio.h"
#include "my_update.h"
#include "protocol.h"
#include "sql_handle.h"
#include "config.h"
#include "my_video.h"
#include "my_mixer.h"
#include "sensor_detector.h"
#include "form_videolayer.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*/
/**
* @brief MiniGUIMain 主函数入口
*
* @param argc
* @param argv[]
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
int MiniGUIMain(int argc, const char* argv[])
{
printf("stat--->%s,%s\n",DEVICE_SVERSION,g_config.k_version);
debugInit();
configLoad();
sqlInit();
gpioInit();
myMixerInit();
myVideoInit();
myUpdateInit();
sensorDetectorInit();
protocolInit();
formVideoLayerCreate();
return 0;
}
<file_sep>/src/drivers/linklist.c
/*
* =====================================================================================
*
* Filename: LinkList.c
*
* Description: 通用链表函数
*
* Version: 1.0
* Created: 2015-11-04 17:28:56
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
/* ----------------------------------------------------------------*
* include head files
*-----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include "linklist.h"
#include "debug.h"
/* ----------------------------------------------------------------*
* extern variables declare
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*
* internal functions declare
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*
* macro define
*-----------------------------------------------------------------*/
typedef struct node {
void * data;
struct node * next;
}ChainNode;
typedef struct _ListPriv {
ChainNode *head; // 头节点
int nodesize; // 数据大小
ChainNode *tail; // 尾节点
ChainNode *temp; // foreach 暂存节点
}ListPriv;
/* ----------------------------------------------------------------*
* variables define
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*/
/**
* @brief newChainNode 新建链表节点
*
* @param data 节点数据
*
* @returns 1成功 0失败
*/
/* ----------------------------------------------------------------*/
static ChainNode * newChainNode(void * data)
{
ChainNode * pChain = 0;
pChain = ( ChainNode * )calloc(1, sizeof(ChainNode) );
if( !pChain ) {
DPRINT("Err: [%s] malloc fail\n", __FUNCTION__);
return 0;
}
pChain->data = data;
pChain->next = 0;
return pChain;
}
/* ----------------------------------------------------------------*/
/**
* @brief listAppend 追加链表元素
*
* @param This 目标链表
* @param pos 加入的数据
*
* @returns 1成功 0失败
*/
/* ----------------------------------------------------------------*/
static int listAppend(List * This,void *pos)
{
ChainNode * newpt = 0;
void * data;
if( !This )
return LISTLINK_FAIL;
data = (void *)malloc(This->priv->nodesize);
if( !data )
return LISTLINK_FAIL;
memcpy(data,pos,This->priv->nodesize);
newpt = newChainNode(data);
if( !newpt ) {
free(data);
return LISTLINK_FAIL;
}
if (!This->priv->head) {
This->priv->head = newpt;
This->priv->tail = This->priv->head;
} else {
This->priv->tail->next = newpt;
This->priv->tail = newpt;
}
return LISTLINK_OK;
}
/* ----------------------------------------------------------------*/
/**
* @brief listGetAddr 取得编号为n的元素所在地址
*
* @param This 目标链表
* @param n 目标编号位置
*
* @returns 1成功 0失败
*/
/* ----------------------------------------------------------------*/
static ChainNode * listGetAddr(List * This,int n)
{
ChainNode * pt = 0;
int a = 0;
if( n < 0) {
DPRINT("Err: [%s] need n > 0\n", __FUNCTION__);
return NULL;
}
pt = This->priv->head;
while( pt && a < n ) {
pt = pt->next;
a++;
}
return pt;
}
/* ----------------------------------------------------------------*/
/**
* @brief listInsert 加入元素
*
* @param This 目标链表
* @param n 加入位置,当前链表后移
* @param pos 加入的数据
*
* @returns 1成功 0失败
*/
/* ----------------------------------------------------------------*/
static int listInsert(List * This, int n ,void *pos)
{
ChainNode * pt = NULL;
ChainNode * newpt = NULL;
void * data = NULL;
// 数据先分配内存拷贝,再创建新节点
data = (void*)malloc(This->priv->nodesize);
if( !data )
goto insert_err;
memcpy(data,pos,This->priv->nodesize);
newpt = newChainNode(data);
if( !newpt )
return LISTLINK_FAIL;
if (n == 0) {
pt = This->priv->head;
This->priv->head = newpt;
This->priv->head->next = pt;
} else {
pt = listGetAddr( This, n-1 );
}
if( !pt )
goto insert_err;
newpt->next = pt->next;
pt->next = newpt;
return LISTLINK_OK;
insert_err:
if (newpt)
free(newpt);
if (data)
free(data);
return LISTLINK_FAIL;
}
/* ----------------------------------------------------------------*/
/**
* @brief listGetElem 取得第几个元素的值
*
* @param This 目标链表
* @param n 取得元素的位置
* @param data 取得元素的数据
*
* @returns 1成功 0失败
*/
/* ----------------------------------------------------------------*/
static int listGetElem(List * This,int n,void * data)
{
ChainNode * pt = 0;
if( !data )
return LISTLINK_FAIL;
pt = listGetAddr(This,n);
if( ! pt )
return LISTLINK_FAIL;
memcpy(data, pt->data ,This->priv->nodesize);
return LISTLINK_OK;
}
/* ----------------------------------------------------------------*/
/**
* @brief listGetElemTail 取得最后一个元素的数据
*
* @param This 目标链表
*
* @returns 元素内容
*/
/* ----------------------------------------------------------------*/
static int listGetElemTail(List *This,void *data)
{
if (!data) {
DPRINT("data is null\n");
return LISTLINK_FAIL;
}
memcpy(data, This->priv->tail->data ,This->priv->nodesize);
return LISTLINK_OK;
}
/* ----------------------------------------------------------------*/
/**
* @brief listTraverseList 遍历访问,访问某个节点元素用函数处理
*
* @param This 目标链表
* @param func 访问该节点元素的处理函数
*
* @returns 1成功 0失败
*/
/* ----------------------------------------------------------------*/
static int listTraverseList(List* This,int (*func)(void * ))
{
ChainNode * pt = 0;
int a=0;
if( !(This && This->priv->head) )
return LISTLINK_FAIL;
for( a = 0 ,pt = This->priv->head->next; pt ; pt = pt->next ) {
if( ! func( (pt->data)) )
return a+1;
a++;
}
return LISTLINK_FAIL;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief listForeachStart 链表遍历开始
*
* @param This
* @param n 从链表第几个下标开始 首地址为1
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int listForeachStart(List* This,int n)
{
if (n < 0) {
DPRINT("Err: [%s] need n > 0\n",__FUNCTION__ );
This->priv->temp = NULL;
return LISTLINK_FAIL;
}
This->priv->temp = listGetAddr(This,n);
return LISTLINK_OK;
}
static int listForeachNext(List* This)
{
This->priv->temp = This->priv->temp->next;
return LISTLINK_OK;
}
static int listForeachGetElem(List* This,void *data)
{
if (!This->priv->temp)
return LISTLINK_FAIL;
memcpy(data, This->priv->temp->data ,This->priv->nodesize);
return LISTLINK_OK;
}
static int listForeachEnd(List* This)
{
if (This->priv->temp)
return LISTLINK_OK;
else
return LISTLINK_FAIL;
}
/* ----------------------------------------------------------------*/
/**
* @brief listDelete 删除第几个元素
*
* @param This 目标链表
* @param n 删除元素位置
*
* @returns 1成功 0失败
*/
/* ----------------------------------------------------------------*/
static int listDelete( List * This, int n )
{
ChainNode * pt =0;
ChainNode * pf=0;
if (!This->priv->head) {
DPRINT("Err: [%s] empty list \n",__FUNCTION__);
return LISTLINK_FAIL;
}
if (n == 0) {
pf = This->priv->head;
This->priv->head = pf->next;
goto delete_end;
} else {
pt = listGetAddr( This,n-1 );
}
if( !(pt && pt->next ))
return LISTLINK_FAIL;
if ( pt->next == This->priv->tail )
This->priv->tail = pt;
pf = pt->next;
pt->next = pt->next->next;
delete_end:
if (pf) {
if (pf->data)
free(pf->data);
free(pf);
}
return LISTLINK_OK;
}
/* ----------------------------------------------------------------*/
/**
* @brief listClearList 清空链表
*
* @param This 目标链表
*/
/* ----------------------------------------------------------------*/
static void listClearList(List * This)
{
while ( listDelete(This,0) == LISTLINK_OK );
}
/* ----------------------------------------------------------------*/
/**
* @brief listDestory 销毁链表
*
* @param This 销毁对象
*/
/* ----------------------------------------------------------------*/
static void listDestory(List * This)
{
This->clear(This);
free(This->priv->head);
This->priv->head = 0;
free(This->priv);
free(This);
This = 0;
}
/* ----------------------------------------------------------------*/
/**
* @brief CreateList 创建链表
*
* @param size 数据长度
*
* @returns 创建的链表
*/
/* ----------------------------------------------------------------*/
List *listCreate(unsigned int size )
{
List * This = 0;
// void * data = 0;
This=(List*)calloc(1, sizeof(List) );
if( !This )
return LISTLINK_FAIL;
This->priv = (ListPriv *)calloc(1,sizeof(ListPriv));
if (!This->priv) {
free(This);
return LISTLINK_FAIL;
}
This->priv->head = 0;//newChainNode(data );
// if( ! This->priv->head ) {
// free(This);
// return LISTLINK_FAIL;
// }
This->priv->nodesize = size;
This->priv->tail = This->priv->head;
This->clear = listClearList;
This->append = listAppend;
This->insert = listInsert;
This->delete = listDelete;
This->foreachStart = listForeachStart;
This->foreachNext = listForeachNext;
This->foreachGetElem = listForeachGetElem;
This->foreachEnd = listForeachEnd;
This->getElem = listGetElem;
This->getElemTail = listGetElemTail;
This->traverse = listTraverseList;
This->destory = listDestory;
return This;
}
#ifdef TEST
int main(int argc, char *argv[])
{
char *a = "123";
char *a1 = "223";
char *a2 = "323";
char *a3 = "423";
List *plist = listCreate(sizeof(char *));
plist->append(plist,&a);
plist->append(plist,&a1);
plist->append(plist,&a2);
plist->insert(plist,1,&a3);
plist->delete(plist,3);
char *b;
if (plist->getElemTail(plist,&b) == LISTLINK_OK)
DPRINT("[get tail]%s\n", b);
if (plist->getElem(plist,0,&b) == LISTLINK_OK)
DPRINT("[get elem]%s\n", b);
plist->foreachStart(plist,0);
while(plist->foreachEnd(plist)) {
char *c;
plist->foreachGetElem(plist,&c);
DPRINT("[foreach]%s\n", c);
plist->foreachNext(plist);
}
return 0;
}
#endif
<file_sep>/src/app/udp_talk/udp_talk_parse.h
#ifndef TLINK_SIP
#ifndef RTPObjectH
#define RTPObjectH
#include <stdint.h>
#include "udp_client.h"
//---------------------------------------------------------------------------
#define MAXENCODEPACKET (200*1024-16)
typedef struct {
unsigned int packet_cnt; //分包数量
unsigned int packet_size; //分包大小
unsigned int packet_idx; //包索引
unsigned int alen; //audio长度
unsigned int atype;
unsigned int tlen; //数据长度
unsigned int dead;
unsigned int seq; //帧序号
unsigned int slen; //第一帧长度
unsigned int vtype; //第一帧类型
unsigned int checksum; // 校验和
unsigned char sdata[MAXENCODEPACKET]; //帧数据
}rec_body;
#define RECBODYSIZE ((unsigned int)sizeof(rec_body))
#define RECHEADSIZE ((unsigned int)(sizeof(rec_body)-MAXENCODEPACKET))
typedef struct _TRTPObject
{
unsigned int SendPacketIdx;
int Terminate;
int RecvTimeOut;
TUDPClient *udp;
char cPeerIP[16];
char cMasterDevIP[16];
char ViceDeviceIP[16];
char cServerIP[16];
// int ServerPort;
int dwPeerIP;
unsigned int dwMasterDevIP;
unsigned int dwWEBSrvIP;
uint8_t bRecvLocalPacket; //是否接收到直传的包
int PeerPort;
int bInternet; //是否基于互联网的传输
uint8_t bTransBySrv; //是否通过服务器中转包
int LostFramePrecent; //丢包率
int DelayTime; //延迟时间
int SendPacketCnt; //发送统计
void (* Destroy)(struct _TRTPObject *This);
int (* RecvBuffer)(struct _TRTPObject *This,void *buf,int count,int TimeOut);
int (* SendBuffer)(struct _TRTPObject *This,void *buf,int count);
int (* test)(struct _TRTPObject *This,void *buf,int count);
void (*SetPeerPort)(struct _TRTPObject *This,int PeerPort);
int (*SendPortNumber)(struct _TRTPObject *This,const char *IP,int Port,
const char *SrvIP,unsigned int UserID);
} TRTPObject;
//---------------------------------------------------------------------------
// 创建一个UDP客户端,Port为0则不绑定端口
TRTPObject* TRTPObject_Create(const char *PeerIP,int PeerPort);
#endif
#endif
<file_sep>/src/wireless/my_mqtt.h
/*
* =============================================================================
*
* Filename: my_mqtt.h
*
* Description: 封装mqtt接口
*
* Version: 1.0
* Created: 2019-05-21 11:34:04
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_MQTT_H
#define _MY_MQTT_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef struct _MyMqtt {
int (*send)(char *pub_topic,int len,void *payload);
int (*subcribe)(char* topic,
void (*onSuccess)(void * context),
void (*onFailure)(void *context) );
int (*connect)(char *url,char *client_id, int keepalive_interval,char *username,char *password,
int (*callBack)(void* context, char* topicName, int topicLen, void* payload),
void (*onSuccess)(void * context),
void (*onFailure)(void *context) );
}MyMqtt;
MyMqtt * myMqttCreate(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/module/updater/updater.h
#ifndef _RKUPDATER_H_
#define _RKUPDATER_H_
#include "httpd.h"
#include "partition.h"
enum {
UPDATE_UNKONW = 0,
UPDATE_KERNEL,
UPDATE_DTB,
UPDATE_USERDATA,
UPDATE_BOOT,
UPDATE_ALL,
};
class Updater
{
public:
int showTip(char *tipcap);
int prepare();
int download(char* url);
int download(int url_type);
int checkEnvironment(char *path,int url_type);
int runCmd(char* cmd);
int waitAppEixt(char *app_name);
int doUpdate(int type);
Updater();
~Updater();
RKPartition* mpart;
RKDisplay *mdisp;
char *updateimg[256];
char *updateimgmd5[256];
};
#endif
<file_sep>/src/gui/my_controls/my_scroll.h
/*
* =============================================================================
*
* Filename: my_scroll.h
*
* Description: 自定义滚轮选择
*
* Version: 1.0
* Created: 2019-04-23 19:46:14
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_SCROLL_H
#define _MY_SCROLL_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include "my_controls.h"
#include "commongdi.h"
#include "my_button.h"
#define CTRL_MYSCROLL ("myscroll")
// 定义总共多少行,只能为奇数
#define MYSCROLL_MAX_LINES 3
enum {
MSG_SET_NUM = MSG_USER + 1,
MSG_GET_NUM,
};
struct ScrollText {
RECT rc; // N行文字坐标
int num;
};
typedef struct {
const char *text; // 文字
int flag; // 类型
PLOGFONT font; // 字体
int index_start,index_end,index_center; // 数字范围
struct ScrollText rc_text[MYSCROLL_MAX_LINES]; // N行文字坐标
}MyScrollCtrlInfo;
typedef struct _MyCtrlScroll{
HWND idc; // 控件ID
int flag; // 类型
char *text; // 数字旁的中文后缀
int index_start,index_end; // 数字范围
int x,y,w,h;
PLOGFONT font; // 字体
}MyCtrlScroll;
HWND createMyScroll(HWND hWnd,MyCtrlScroll *button);
extern MyControls *my_scroll;
void initMyScroll(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/module/singlechip/s_config.c
#include <sys/ioctl.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include "config.h"
#include "iniparser/iniparser.h"
#define DPRINT(...) \
do { \
printf("\033[1;34m"); \
printf("[UART->%s,%d]",__func__,__LINE__); \
printf(__VA_ARGS__); \
printf("\033[0m"); \
} while (0)
#define SIZE_CONFIG(x) x,sizeof(x) - 1
#define NELEMENTS(array) (sizeof (array) / sizeof ((array) [0]))
static dictionary* cfg_private_ini = NULL;
static dictionary* cfg_public_ini = NULL;
static void configLoadEtcInt(dictionary *cfg_ini, EtcValueInt *etc_file,
unsigned int length);
static int brightness = 0;
static struct CapType cap; // 抓拍或录像
static char imei[64 + 1]; // 太川设备机身码
static struct Mute mute;
static EtcValueInt etc_public_int[]={
{"cap_doorbell","type", &cap.type, 0},
{"cap_doorbell","count", &cap.count, 1},
{"cap_doorbell","timer", &cap.timer, 5},
{"others", "brightness", &brightness, 80},
{"rings", "mute_state", &mute.state, 0},
{"rings", "mute_start_time", &mute.start_time, 0},
{"rings", "mute_end_time", &mute.end_time, 1439},
};
static EtcValueChar etc_private_char[]={
{"device", "imei", SIZE_CONFIG(imei), "0"},
};
static char *sec_private[] = {"device",NULL};
static char *sec_public[] = {"cap_doorbell","others","rings",NULL};
/* ---------------------------------------------------------------------------*/
/**
* @brief configoadEtcInt 加载int型配置文件
*
* @param etc_file 文件数组地址
* @param length 数组长度
*/
/* ---------------------------------------------------------------------------*/
static void configLoadEtcInt(dictionary *cfg_ini, EtcValueInt *etc_file,
unsigned int length)
{
unsigned int i;
char buf[64];
for (i=0; i<length; i++) {
sprintf(buf,"%s:%s",etc_file->section,etc_file->key);
*etc_file->value = iniparser_getint(cfg_ini, buf, etc_file->default_int);
DPRINT("%s,%d\n", buf,*etc_file->value);
etc_file++;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief sconfigLoadEtcChar 加载char型配置文件
*
* @param etc_file 文件数组地址
* @param length 数组长度
*/
/* ---------------------------------------------------------------------------*/
static void sconfigLoadEtcChar(dictionary *cfg_ini, EtcValueChar *etc_file,
unsigned int length)
{
unsigned int i;
char buf[64];
for (i=0; i<length; i++) {
sprintf(buf,"%s:%s",etc_file->section,etc_file->key);
strncpy(etc_file->value,
iniparser_getstring(cfg_ini, buf, etc_file->default_char),
etc_file->leng);
// DPRINT("[%s]%s,%s\n", __FUNCTION__,buf,etc_file->value);
etc_file++;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief loadIniFile 加载ini文件,同时检测字段完整性
*
* @param d
* @param file_path
* @param sec[]
*
* @returns >0 有缺少字段,需要保存更新, 0无缺少字段,正常
*/
/* ---------------------------------------------------------------------------*/
static int loadIniFile(dictionary **d,char *file_path,char *sec[])
{
int ret = 0;
int i;
*d = iniparser_load(file_path);
if (*d == NULL) {
*d = dictionary_new(0);
assert(*d);
ret++;
for (i=0; sec[i] != NULL; i++)
iniparser_set(*d, sec[i], NULL);
} else {
int nsec = iniparser_getnsec(*d);
int j;
const char * secname;
for (i=0; sec[i] != NULL; i++) {
for (j=0; j<nsec; j++) {
secname = iniparser_getsecname(*d, j);
if (strcasecmp(secname,sec[i]) == 0)
break;
}
if (j == nsec) {
ret++;
iniparser_set(*d, sec[i], NULL);
}
}
}
return ret;
}
void sconfigLoad(void)
{
loadIniFile(&cfg_private_ini,CONFIG_FILENAME,sec_private);
sconfigLoadEtcChar(cfg_private_ini,etc_private_char,NELEMENTS(etc_private_char));
iniparser_freedict(cfg_private_ini);
loadIniFile(&cfg_public_ini,CONFIG_PARA_FILENAME,sec_public);
configLoadEtcInt(cfg_public_ini,etc_public_int,NELEMENTS(etc_public_int));
iniparser_freedict(cfg_public_ini);
}
int getCapType(void)
{
return cap.type;
}
int getCapCount(void)
{
return cap.count;
}
int getCapTimer(void)
{
return cap.timer;
}
char * getCapImei(void)
{
return imei;
}
int getBrightness(void)
{
return brightness;
}
int sIsNeedToPlay(void)
{
if (mute.state == 0)
return 1;
time_t timer;
timer = time(&timer);
struct tm *tm = localtime(&timer);
int time_now = tm->tm_hour * 60 + tm->tm_min;
if (mute.start_time <= mute.end_time) {
if (time_now >= mute.start_time && time_now <= mute.end_time)
return 0;
else
return 1;
} else {
if (time_now <= mute.end_time)
return 0;
if (time_now >= mute.start_time)
return 0;
return 1;
}
}
<file_sep>/src/app/udp_talk/udp_talk_transport.h
/*
* =============================================================================
*
* Filename: Rtp.h
*
* Description: 传输接口
*
* Version: 1.0
* Created: 2016-03-01 14:28:41
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* ============================================================================
*/
#ifndef _RTP_H
#define _RTP_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
struct _UdpTalkTransInterface;
typedef struct _Rtp {
int fpAudio; //音频驱动打开句柄
int bTransVideo;//是否传输视频
int bTransAudio;//是否传输音频
int silence; //静音模式
int frame_period;// 帧率
int video_codec_type; //视频编码类型
struct _UdpTalkTransInterface *interface;
int *(*getFpAudio)(struct _Rtp *);
int (*setPeerIp)(struct _Rtp *,char *ip);
void (*setSilence)(struct _Rtp *,int value);
int (*getSilence)(struct _Rtp *);
int (*init)(struct _Rtp *, const char *dest_ip, int Port);
void (*buildConnect)(struct _Rtp *);
int (*getVideo)(struct _Rtp *,void *data);
void (*startAudio)(struct _Rtp *);
void (*close)(struct _Rtp *);
void (*Destroy)(struct _Rtp **);
} Rtp;
// 需要实现的接口
typedef struct _UdpTalkTransInterface {
void (*abortCallBack)(struct _Rtp *);
void (*start)(struct _Rtp *);
void (*receiveAudio)(struct _Rtp *,void *data,int size);
void (*receiveEnd)(struct _Rtp *);
void (*sendStart)(struct _Rtp *);
void (*sendVideo)(struct _Rtp *,void *data,int size);
int (*sendAudio)(struct _Rtp *,void *data,int size);
void (*sendEnd)(struct _Rtp *);
}UdpTalkTransInterface;
Rtp * createRtp(UdpTalkTransInterface *,void *callBackData);
extern Rtp * udp_talk_trans;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/gui/my_controls/my_scroll.c
/*
* =====================================================================================
*
* Filename: MyScroll.c
*
* Description: 自定义按钮
*
* Version: 1.0
* Created: 2015-12-09 16:22:37
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
/* ----------------------------------------------------------------*
* include head files
*-----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include "my_scroll.h"
#include "debug.h"
#include "cliprect.h"
#include "internals.h"
#include "ctrlclass.h"
/* ----------------------------------------------------------------*
* extern variables declare
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*
* internal functions declare
*-----------------------------------------------------------------*/
static int myScrollControlProc (HWND hwnd, int message, WPARAM wParam, LPARAM lParam);
static void buttonTopPress(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonBottomPress(HWND hwnd, int id, int nc, DWORD add_data);
/* ----------------------------------------------------------------*
* macro define
*-----------------------------------------------------------------*/
#define CTRL_NAME CTRL_MYSCROLL
#define BMP_LOCAL_PATH "setting/"
enum {
IDC_BUTTON_TOP = 1,
IDC_BUTTON_BOTTOM,
};
/* ----------------------------------------------------------------*
* variables define
*-----------------------------------------------------------------*/
MyControls *my_scroll;
static MyCtrlButton ctrls_button[] = {
{IDC_BUTTON_TOP, MYBUTTON_TYPE_TWO_STATE|MYBUTTON_TYPE_TEXT_NULL,"top",0, 0,buttonTopPress},
{IDC_BUTTON_BOTTOM, MYBUTTON_TYPE_TWO_STATE|MYBUTTON_TYPE_TEXT_NULL,"bottom",0,200,buttonBottomPress},
{0},
};
/* ---------------------------------------------------------------------------*/
/**
* @brief myScrollRegist 注册控件
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static BOOL myScrollRegist (void)
{
WNDCLASS WndClass;
WndClass.spClassName = CTRL_NAME;
WndClass.dwStyle = WS_NONE;
WndClass.dwExStyle = WS_EX_NONE;
WndClass.hCursor = GetSystemCursor (IDC_ARROW);
WndClass.iBkColor = 0;
WndClass.WinProc = myScrollControlProc;
return RegisterWindowClass(&WndClass);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myScrollCleanUp 卸载控件
*/
/* ---------------------------------------------------------------------------*/
static void myScrollCleanUp (void)
{
UnregisterWindowClass(CTRL_NAME);
}
static void buttonTopPress(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
PCONTROL pCtrl = Control (GetParent(hwnd));
MyScrollCtrlInfo* pInfo = (MyScrollCtrlInfo*)(pCtrl->dwAddData2);
int num = pInfo->rc_text[pInfo->index_center].num;
if (num >= pInfo->index_end)
SendMessage(GetParent(hwnd),MSG_SET_NUM,pInfo->index_start,0);
else
SendMessage(GetParent(hwnd),MSG_SET_NUM,++num,0);
}
static void buttonBottomPress(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
PCONTROL pCtrl = Control (GetParent(hwnd));
MyScrollCtrlInfo* pInfo = (MyScrollCtrlInfo*)(pCtrl->dwAddData2);
int num = pInfo->rc_text[pInfo->index_center].num;
if (num <= pInfo->index_start)
SendMessage(GetParent(hwnd),MSG_SET_NUM,pInfo->index_end,0);
else
SendMessage(GetParent(hwnd),MSG_SET_NUM,--num,0);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief paint 主要绘图函数
*
* @param hWnd
* @param hdc
*/
/* ---------------------------------------------------------------------------*/
static void paint(HWND hWnd,HDC hdc)
{
RECT rc_bmp,*rc_text;
PCONTROL pCtrl;
pCtrl = Control (hWnd);
GetClientRect (hWnd, &rc_bmp);
rc_text = &rc_bmp;
MyScrollCtrlInfo* pInfo = (MyScrollCtrlInfo*)(pCtrl->dwAddData2);
if (!pCtrl->dwAddData2)
return;
SetBkMode(hdc,BM_TRANSPARENT);
SetTextColor(hdc,COLOR_lightwhite);
SelectFont (hdc, pInfo->font);
SetPenColor (hdc, 0xCCCCCC);
int i;
char buf[6] = {0};
for (i=0; i<MYSCROLL_MAX_LINES; i++) {
if (i != MYSCROLL_MAX_LINES - 1) {
MoveTo (hdc, pInfo->rc_text[i].rc.left, pInfo->rc_text[i].rc.bottom);
LineTo (hdc, pInfo->rc_text[i].rc.right, pInfo->rc_text[i].rc.bottom);
}
sprintf(buf,"%d",pInfo->rc_text[i].num);
DrawText (hdc,buf, -1, &pInfo->rc_text[i].rc,
DT_CENTER | DT_VCENTER | DT_WORDBREAK | DT_SINGLELINE);
if (i == pInfo->index_center) {
DrawText (hdc,pInfo->text, -1, &pInfo->rc_text[i].rc,
DT_RIGHT | DT_VCENTER | DT_WORDBREAK | DT_SINGLELINE);
}
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myScrollControlProc 控件主回调函数
*
* @param hwnd
* @param message
* @param wParam
* @param lParam
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int myScrollControlProc (HWND hwnd, int message, WPARAM wParam, LPARAM lParam)
{
int i;
HDC hdc;
PCONTROL pCtrl;
DWORD dwStyle;
RECT rc;
MyScrollCtrlInfo* pInfo;
pCtrl = Control (hwnd);
pInfo = (MyScrollCtrlInfo*)pCtrl->dwAddData2;
dwStyle = GetWindowStyle (hwnd);
switch (message) {
case MSG_CREATE:
{
MyScrollCtrlInfo* data = (MyScrollCtrlInfo*)pCtrl->dwAddData;
pInfo = (MyScrollCtrlInfo*) calloc (1, sizeof (MyScrollCtrlInfo));
if (pInfo == NULL)
return -1;
memset(pInfo,0,sizeof(MyScrollCtrlInfo));
pInfo->flag = data->flag;
pInfo->text = data->text;
pInfo->font = data->font;
pInfo->index_start = data->index_start;
pInfo->index_end = data->index_end;
pInfo->index_center = MYSCROLL_MAX_LINES/2;
GetClientRect (hwnd, &rc);
int text_hight = RECTH(rc) - (ctrls_button[0].image_press.bmHeight * 2);
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
ctrls_button[i].x = rc.left + (RECTW(rc) - ctrls_button[i].image_press.bmWidth) / 2;
ctrls_button[i].y = rc.top + i*(ctrls_button[i].image_press.bmHeight + text_hight);
createMyButton(hwnd,&ctrls_button[i]);
}
for (i=0; i<MYSCROLL_MAX_LINES; i++) {
pInfo->rc_text[i].rc.left = rc.left;
pInfo->rc_text[i].rc.right = rc.right;
pInfo->rc_text[i].rc.top = rc.top + i*text_hight/MYSCROLL_MAX_LINES + ctrls_button[0].image_press.bmHeight;
pInfo->rc_text[i].rc.bottom = pInfo->rc_text[i].rc.top + text_hight/MYSCROLL_MAX_LINES;
}
pCtrl->dwAddData2 = (DWORD)pInfo;
return 0;
}
case MSG_DESTROY:
free(pInfo);
break;
case MSG_PAINT:
hdc = BeginPaint (hwnd);
paint(hwnd,hdc);
EndPaint (hwnd, hdc);
return 0;
case MSG_SET_NUM:
{
int i;
pInfo->rc_text[pInfo->index_center].num = wParam;
if (pInfo->index_center < 1)
break;
for (i=pInfo->index_center-1; i>=0; i--) {
pInfo->rc_text[i].num = wParam - 1;
if (pInfo->rc_text[i].num < pInfo->index_start) {
pInfo->rc_text[i].num =
pInfo->index_end - (pInfo->index_start - pInfo->rc_text[i].num) + 1;
}
}
for (i=pInfo->index_center+1; i<MYSCROLL_MAX_LINES; i++) {
pInfo->rc_text[i].num = wParam + 1;
if (pInfo->index_end < pInfo->rc_text[i].num) {
pInfo->rc_text[i].num =
pInfo->index_start + (pInfo->rc_text[i].num - pInfo->index_end) - 1;
}
}
InvalidateRect (hwnd, NULL, TRUE);
} break;
case MSG_GET_NUM:
{
return pInfo->rc_text[pInfo->index_center].num;
} break;
default:
break;
}
return DefaultControlProc (hwnd, message, wParam, lParam);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief bmpsMainScrollLoad 加载主界面图片
*
* @param controls
**/
/* ---------------------------------------------------------------------------*/
static void myScrollBmpsLoad(void *ctrls,char *path)
{
my_button->bmpsLoad(ctrls_button,BMP_LOCAL_PATH);
}
static void myScrollBmpsRelease(void *ctrls)
{
my_button->bmpsRelease(ctrls_button);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief createMyScroll 创建单个皮肤按钮
*
* @param hWnd
* @param id
* @param x,y,w,h 坐标
* @param image_normal 正常图片
* @param image_press 按下图片
* @param display 是否显示 0不显示 1显示
* @param mode 是否为选择模式 0非选择 1选择
* @param notif_proc 回调函数
*/
/* ---------------------------------------------------------------------------*/
HWND createMyScroll(HWND hWnd,MyCtrlScroll *ctrl)
{
HWND hCtrl;
MyScrollCtrlInfo pInfo;
pInfo.flag = ctrl->flag;
pInfo.text = ctrl->text;
pInfo.font = ctrl->font;
pInfo.index_start = ctrl->index_start;
pInfo.index_end = ctrl->index_end;
hCtrl = CreateWindowEx(CTRL_NAME,"",WS_VISIBLE|WS_CHILD,WS_EX_TRANSPARENT,
ctrl->idc,ctrl->x,ctrl->y,ctrl->w,ctrl->h, hWnd,(DWORD)&pInfo);
return hCtrl;
}
void initMyScroll(void)
{
my_scroll = (MyControls *)malloc(sizeof(MyControls));
my_scroll->regist = myScrollRegist;
my_scroll->unregist = myScrollCleanUp;
my_scroll->bmpsLoad = myScrollBmpsLoad;
my_scroll->bmpsRelease = myScrollBmpsRelease;
}
<file_sep>/src/app/rdface/readsense_face_sdk.h
#ifndef READSENSE_FACE_SDK_H
#define READSENSE_FACE_SDK_H
#define RSFT_MAX_FACE_NUM 10
#define FACE_LANDMARK_NUM 21
#define FACE_RECOGNITION_FEATURE_DIMENSION 512
#ifdef __cplusplus
extern "C" {
#endif
const char * readsense_face_sdk_get_version_number();
const char * readsense_face_sdk_get_device_key();
//detect_frequency: recommend [5,20]
int readsense_initial_face_sdk(void * model_virt,
const int detect_frequency, const int detect_frequency_noface,
const char * fd_weights_path, const char * fl_weights_path,
const char * fle_light_weights_path, const char * fle_infrared_weights_path,
const char * fgs_weights_path, const char * fr_weights_path,
const char * fr_lite_weights_path, const char * fq_weights_path,
const char * fla_weights_path, const char * fgas_weights_path,
const char * app_id, const char * signature);
enum {
RSFT_DETECT_FRAME_RETURN_VALUE = 1001,
RSFT_TRACK_FRAME_RETURN_VALUE = 0,
RSFT_LICENCE_VALIDATE_FAIL = 1
};
typedef struct tag_RSFT_FACE_RESULT
{
int track_id;
int left;
int top;
int right;
int bottom;
float blur_prob;
float front_prob;
float face_landmark[FACE_LANDMARK_NUM*2];
int gender;//0: female, 1: male, -1: invalid value
int age;//>=0, -1: invalid value
} RSFT_FACE_RESULT;
int readsense_face_tracking(void * model_virt, void * model_phys, void * raw_virt, void * raw_phys,
void * dst_virt, void * dst_phys, void * internal_virt, void * internal_phys,
int dsp_fd, int raw_width, int raw_height);
// sample code of getting result after invoking <readsense_face_tracking>:
/*
int face_num = *((int*)(dst_virt));
printf("face_num:%d\n", face_num);
RSFT_FACE_RESULT * pFTResult = (RSFT_FACE_RESULT *)((int*)(dst_virt) + 1);
for (int i = 0; i < face_num; i++)
{
printf("facenum %d: %d,%d,%d,%d, track_id:%d\n", i, pFTResult[i].left, pFTResult[i].top,
pFTResult[i].right, pFTResult[i].bottom, pFTResult[i].track_id);
printf("blur:%f, front:%f\n", pFTResult[i].blur_prob, pFTResult[i].front_prob);
printf("face_landmark:\n");
for (int k = 0; k < FACE_LANDMARK_NUM;k++)
{
printf("%f,%f\n", pFTResult[i].face_landmark[k*2], pFTResult[i].face_landmark[k*2+1]);
}
}
*/
int readsense_clear_tracking_state();
//reserve for debug, don't use generally.
int readsense_face_detection(void * model_virt, void * model_phys, void * raw_virt, void * raw_phys,
void * dst_virt, void * dst_phys, void * internal_virt, void * internal_phys,
int dsp_fd, int raw_width, int raw_height);
//reserve for debug, don't use generally.
int readsense_face_detection_and_landmark(void * model_virt, void * model_phys, void * raw_virt, void * raw_phys,
void * dst_virt, void * dst_phys, void * internal_virt, void * internal_phys,
int dsp_fd, int raw_width, int raw_height);
int readsense_face_quality(void * model_virt, void * model_phys,
void * raw_virt, void * raw_phys, void * dst_virt, void * dst_phys,
void * internal_virt, void * internal_phys, int dsp_fd, int raw_width, int raw_height,
float * landmark_position);
/*
printf("face quality: %f\n", *((float *)dst_virt));
*/
int readsense_face_liveness_infrared(void * model_virt, void * model_phys,
void * raw_virt, void * raw_phys, void * dst_virt, void * dst_phys,
void * internal_virt, void * internal_phys, int dsp_fd, int raw_width, int raw_height,
float * landmark_position);
/*
printf("face liveness: %d\n", *((int *)dst_virt));
*/
int readsense_face_liveness_light(void * model_virt, void * model_phys,
void * raw_virt, void * raw_phys, void * dst_virt, void * dst_phys,
void * internal_virt, void * internal_phys, int dsp_fd, int raw_width, int raw_height,
float * landmark_position);
/*
printf("face liveness: %d\n", *((int *)dst_virt));
*/
int readsense_face_recognition_lite(void * model_virt, void * model_phys,
void * raw_virt, void * raw_phys, void * dst_virt, void * dst_phys,
void * internal_virt, void * internal_phys, int dsp_fd, int raw_width, int raw_height,
float * landmark_position);
/*
printf("fr_feature:\n");
for (int i = 0; i < FACE_RECOGNITION_FEATURE_DIMENSION; i++)
printf("%f,", ((float *)dst_virt)i]);
printf("\n");
*/
#ifdef __cplusplus
}
#endif
#endif
<file_sep>/include/mpi/mpp_sdk_interface.h
/*
* =============================================================================
*
* Filename: mpp_sdk_interface.h
*
* Description: mpp头文件目录
*
* Version: 1.0
* Created: 2019-06-20 15:35:50
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MPP_SDK_INTERFACE_H
#define _MPP_SDK_INTERFACE_H
#include <mpp/rk_type.h>
#include <mpp/rk_mpi.h>
#include <mpp/mpp_err.h>
#include <mpp/mpp_buffer.h>
#endif
<file_sep>/src/gui/form_video.h
/*
* =============================================================================
*
* Filename: form_video.h
*
* Description: 视频通话,录像等
*
* Version: 1.0
* Created: 2019-04-30 14:16:25
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _VIDEO_H
#define _VIDEO_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
enum {
FORM_VIDEO_TYPE_CAPTURE, // 抓拍
FORM_VIDEO_TYPE_RECORD, // 录像
FORM_VIDEO_TYPE_TALK_IN, // 门口机呼入
FORM_VIDEO_TYPE_TALK_OUT, // 门口机呼出
FORM_VIDEO_TYPE_MONITOR, // APP监视
FORM_VIDEO_TYPE_OUTDOOR, // 监视门口
};
int createFormVideo(HWND hVideoWnd,int type,void (*callback)(void),int count);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/drivers/json_dec.c
/*
* =============================================================================
*
* Filename: CjsonDec.c
*
* Description: json编解码封装
*
* Version: v1.0
* Created: 2016-07-06 17:23:16
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "json_dec.h"
#include "debug.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*/
/**
* @brief cjsonJugdeTypeInt 返回整型类型数据
*
* @param data 输入数据
*
* @returns 返回整型值
*/
/* ---------------------------------------------------------------------------*/
static int cjsonJugdeTypeInt(cJSON *data)
{
if (!data) {
return 0;
}
switch (data->type)
{
case cJSON_False: return 0;
case cJSON_True: return 1;
case cJSON_Number: return data->valueint;
default: return 0;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cjsonJugdeTypeChar 返回字符串类型数据
*
* @param data 输入数据
* @param value 输出数据,传入指针地址
*/
/* ---------------------------------------------------------------------------*/
static void cjsonJugdeTypeChar(cJSON *data,char **value)
{
if (!data) {
*value = NULL;
return;
}
switch (data->type)
{
case cJSON_NULL:
{
*value = NULL;
} break;
case cJSON_String:
{
*value = (char *) malloc(strlen(data->valuestring)+1);
//printf("valuestring:%s\n",data->valuestring);
strcpy(*value,data->valuestring);
} break;
default:
break;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cjsonChangeCurrentObj 切换当前json object
*
* @param This
* @param name 项目名字
*/
/* ---------------------------------------------------------------------------*/
int cjsonChangeCurrentObj(CjsonDec *This,char *name)
{
cJSON *data = NULL;
data = cJSON_GetObjectItem(This->current,name);
if(NULL != data)
{
This->front = This->current;
This->current = data;
// printf("data %s\n", data->valuestring);
}
else
{
printf("cjsonChangeCurrentObj failed\n");
return -1;
}
return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cjsonChangeCurrentArrayObj 切换成数组 object
*
* @param This
* @param item 数组序号
*/
/* ---------------------------------------------------------------------------*/
static void cjsonChangeCurrentArrayObj(CjsonDec *This,int item)
{
cJSON *data = NULL;
data = cJSON_GetArrayItem(This->current,item);
This->front = This->current;
This->current = data;
}
static void cjsonChangeObjFront(CjsonDec *This)
{
This->current = This->front;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cjsonGetArraySize 返回数组个数
*
* @param This
*
* @returns 返回个数
*/
/* ---------------------------------------------------------------------------*/
static int cjsonGetArraySize(CjsonDec *This)
{
return cJSON_GetArraySize(This->current);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cjsonGetValueChar 对外接口,返回项目字符串
*
* @param This
* @param name 项目
* @param value 返回字符串的指针地址
*/
/* ---------------------------------------------------------------------------*/
static void cjsonGetValueChar(CjsonDec *This,char *name,char **value)
{
cJSON *data = NULL;
data = cJSON_GetObjectItem(This->current,name);
if(NULL == data)
{
printf("cJSON_GetObjectItem:%s NULL\n", name);
return;
}
cjsonJugdeTypeChar(data,value);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cjsonGetValueInt 对外接口,返回整型
*
* @param This
* @param name 项目
*
* @returns 返回值
*/
/* ---------------------------------------------------------------------------*/
static int cjsonGetValueInt(CjsonDec *This,char *name)
{
cJSON *data = NULL;
data = cJSON_GetObjectItem(This->current,name);
return cjsonJugdeTypeInt(data);
}
static cJSON* cjsonGetValueObject(CjsonDec *This,char *name)
{
return cJSON_GetObjectItem(This->current,name);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cjsonGetArrayInt 对外接口,返回数组中的项目整型值
*
* @param This
* @param item 数组序号
* @param name 项目
*
* @returns 返回整型值
*/
/* ---------------------------------------------------------------------------*/
static int cjsonGetArrayInt(CjsonDec *This,int item,char *name)
{
cJSON *data = NULL;
cJSON *data_array = NULL;
data = cJSON_GetArrayItem(This->current,item);
data_array = cJSON_GetObjectItem(data,name);
return cjsonJugdeTypeInt(data_array);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cjsonGetArrayChar 对外接口,返回数组中的项目的字符串值
*
* @param This
* @param item 数组序号
* @param name 项目
* @param value 指针地址
*/
/* ---------------------------------------------------------------------------*/
static void cjsonGetArrayChar(CjsonDec *This,int item,char *name,char **value)
{
cJSON *data = NULL;
cJSON *data_array = NULL;
data = cJSON_GetArrayItem(This->current,item);
if(NULL == data)
{
printf("cjsonGetArrayChar NULL\n");
return;
}
switch (data->type)
{
case cJSON_Object:
{
data_array = cJSON_GetObjectItem(data,name);
cjsonJugdeTypeChar(data_array,value);
}
break;
case cJSON_String:
{
cjsonJugdeTypeChar(data,value);
}
break;
default:
break;
}
return;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cjsonPrint 格式化打印当前json obj 结构
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void cjsonPrint(CjsonDec *This)
{
char *out = cJSON_Print(This->current);
printf("%s\n", out);
free(out);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cjsonDestroy 销毁json
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void cjsonDestroy(CjsonDec *This)
{
cJSON_Delete(This->root);
free(This);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cjsonDecCreate 创建json类
*
* @param data HTTP获得的所有数据
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
CjsonDec *cjsonDecCreate(char *data)
{
CjsonDec *This = (CjsonDec *) malloc(sizeof(CjsonDec));
This->root = cJSON_Parse(data);
if(NULL == This->root) {
printf("cJSON_Parse failed\n");
return NULL;
}
This->current = This->root;
This->front = This->root;
if (!This->root) {
printf("Error before: [%s]\n",cJSON_GetErrorPtr());
free(This);
return NULL;
}
This->getValueInt = cjsonGetValueInt;
This->getValueChar = cjsonGetValueChar;
This->getArrayInt = cjsonGetArrayInt;
This->getArrayChar = cjsonGetArrayChar;
This->changeCurrentObj = cjsonChangeCurrentObj;
This->getValueObject = cjsonGetValueObject;
This->changeCurrentArrayObj = cjsonChangeCurrentArrayObj;
This->changeObjFront = cjsonChangeObjFront;
This->getArraySize = cjsonGetArraySize;
This->print = cjsonPrint;
This->destroy = cjsonDestroy;
return This;
}
<file_sep>/src/hal/hal_sensor.h
/*
* =============================================================================
*
* Filename: hal_sensor.h
*
* Description: 室内接近传感器
*
* Version: 1.0
* Created: 2019-07-06 15:38:53
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _HAL_SENSOR_H
#define _HAL_SENSOR_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
enum {
HAL_SENSER_ERR = -1,
HAL_SENSOR_INACTIVE,
HAL_SENSOR_ACTIVE,
};
void halSensorInit(void);
int halSensorGetState(void);
void halSensorUninit(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/drivers/timer.c
/*
* =============================================================================
*
* Filename: Timer.c
*
* Description: 定时器
*
* Version: v1.0
* Created: 2016-08-08 18:33:01
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include "timer.h"
#include "thread_helper.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
typedef struct _TimerPriv {
timer_t real_id;
pthread_mutex_t mutex;
int enable;
unsigned int speed;
unsigned int count;
unsigned int count_old;
int thread_end;
void (*func)(void *);
void * arg;
}TimerPriv;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static void timerStart(Timer *This)
{
if (This->priv->enable) {
printf("Timer already start\n");
return;
}
This->priv->count_old = This->priv->count = This->getSystemTick();
This->priv->enable = 1;
}
static void timerStop(Timer *This)
{
if (This->priv->enable == 0) {
printf("Timer stopped\n");
return;
}
This->priv->enable = 0;
}
static int timerIsStop(Timer *This)
{
return This->priv->enable == 0 ?1:0;
}
static void timerDestroy(Timer *This)
{
This->stop(This);
This->realTimerDelete(This);
while (This->priv->thread_end == 0) {
usleep(10000);
}
if (This->priv)
free(This->priv);
if (This)
free(This);
}
static void* timerThread(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
Timer *This = (Timer *)arg;
This->priv->thread_end = 0;
while(This->priv->real_id) {
if (This->priv->enable == 0) {
usleep(10000);
continue ;
}
if ((This->priv->count - This->priv->count_old) >= This->priv->speed) {
if (This->priv->func)
This->priv->func(This->priv->arg);
pthread_mutex_lock(&This->priv->mutex);
This->priv->count_old = This->priv->count;
pthread_mutex_unlock(&This->priv->mutex);
} else {
pthread_mutex_lock(&This->priv->mutex);
This->priv->count = This->getSystemTick();
pthread_mutex_unlock(&This->priv->mutex);
}
usleep(10000);
}
This->priv->thread_end = 1;
return NULL;
}
static int timerHandle(Timer *This)
{
if (This->priv->enable == 0) {
return 0;
}
int ret = 0;
if ((This->priv->count - This->priv->count_old) >= This->priv->speed) {
if (This->priv->func) {
This->priv->func(This->priv->arg);
ret = 1;
}
This->priv->count_old = This->priv->count;
// This->priv->count = 0;
} else {
// This->priv->count++;
This->priv->count = This->getSystemTick();
}
return ret;
}
static unsigned int getSystemTickDefault(void)
{
struct timeval tv;
gettimeofday(&tv,NULL);
return ((tv.tv_usec / 1000) + tv.tv_sec * 1000 );
}
static void timerResetTick(Timer *This)
{
if (This->priv->enable == 0)
return ;
pthread_mutex_lock(&This->priv->mutex);
This->priv->count_old = This->priv->count = This->getSystemTick();
pthread_mutex_unlock(&This->priv->mutex);
}
static void realTimerCreateDefault(Timer *This,double value,void (*function)(int timerid,int arg))
{
pthread_mutexattr_t mutexattr;
// 嵌套式线程锁
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&This->priv->mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
This->priv->real_id = (timer_t)1;
createThread(timerThread,This);
// timer_create (CLOCK_REALTIME, NULL, &This->priv->real_id);
// timer_connect (This->priv->real_id, function,0);
// timer_settime (This->priv->real_id, 0, value, NULL);
}
static void realTimerDeleteDefault(Timer *This)
{
// timer_delete(This->priv->real_id);
This->priv->real_id = 0;
}
Timer * timerCreate(int speed,void (*function)(void *),void *arg)
{
Timer *This = (Timer *) calloc(1,sizeof(Timer));
if (!This) {
printf("timer alloc fail\n");
return NULL;
}
This->priv = (TimerPriv *) calloc(1,sizeof(TimerPriv));
if (!This->priv){
printf("timer alloc fail\n");
free(This);
return NULL;
}
This->priv->speed = speed;
This->priv->func = function;
This->priv->arg = arg;
This->start = timerStart;
This->stop = timerStop;
This->destroy = timerDestroy;
This->handle = timerHandle;
This->getSystemTick = getSystemTickDefault;
This->resetTick = timerResetTick;
This->isStop = timerIsStop;
realTimerCreateDefault(This,0,NULL);
// This->realTimerCreate = realTimerCreateDefault;
This->realTimerDelete = realTimerDeleteDefault;
return This;
}
<file_sep>/src/drivers/qrenc.c
/**
* qrencode - QR Code encoder
*
* QR Code encoding tool
* Copyright (C) 2006-2017 <NAME> <<EMAIL>>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>
#include <png.h>
#include "qrencode.h"
#define INCHES_PER_METER (100.0/2.54)
static int casesensitive = 1;
static int version = 0;
static int size = 8;
static int margin = 4;
static int dpi = 72;
static QRecLevel level = QR_ECLEVEL_L;
static QRencodeMode hint = QR_MODE_8;
static unsigned char fg_color[4] = {0, 0, 0, 255};
static unsigned char bg_color[4] = {255, 255, 255, 255};
enum imageType {
PNG_TYPE,
PNG32_TYPE,
EPS_TYPE,
SVG_TYPE,
XPM_TYPE,
ANSI_TYPE,
ANSI256_TYPE,
ASCII_TYPE,
ASCIIi_TYPE,
UTF8_TYPE,
ANSIUTF8_TYPE,
UTF8i_TYPE,
ANSIUTF8i_TYPE
};
static enum imageType image_type = PNG_TYPE;
static void fillRow(unsigned char *row, int num, const unsigned char color[])
{
int i;
for(i = 0; i < num; i++) {
memcpy(row, color, 4);
row += 4;
}
}
static int writePNG(const QRcode *qrcode, const char *outfile, enum imageType type)
{
static FILE *fp; // avoid clobbering by setjmp.
png_structp png_ptr;
png_infop info_ptr;
png_colorp palette = NULL;
png_byte alpha_values[2];
unsigned char *row, *p, *q;
int x, y, xx, yy, bit;
int realwidth;
realwidth = (qrcode->width + margin * 2) * size;
if(type == PNG_TYPE) {
row = (unsigned char *)malloc((realwidth + 7) / 8);
} else if(type == PNG32_TYPE) {
row = (unsigned char *)malloc(realwidth * 4);
} else {
fprintf(stderr, "Internal error.\n");
return -1;
}
if(row == NULL) {
fprintf(stderr, "Failed to allocate memory.\n");
return -1;
}
if(outfile[0] == '-' && outfile[1] == '\0') {
fp = stdout;
} else {
fp = fopen(outfile, "wb");
if(fp == NULL) {
fprintf(stderr, "Failed to create file: %s\n", outfile);
free(row);
perror(NULL);
return -1;
}
}
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(png_ptr == NULL) {
free(row);
fprintf(stderr, "Failed to initialize PNG writer.\n");
return -1;
}
info_ptr = png_create_info_struct(png_ptr);
if(info_ptr == NULL) {
free(row);
fprintf(stderr, "Failed to initialize PNG write.\n");
return -1;
}
if(setjmp(png_jmpbuf(png_ptr))) {
png_destroy_write_struct(&png_ptr, &info_ptr);
free(row);
fprintf(stderr, "Failed to write PNG image.\n");
return -1;
}
if(type == PNG_TYPE) {
palette = (png_colorp) malloc(sizeof(png_color) * 2);
if(palette == NULL) {
free(row);
fprintf(stderr, "Failed to allocate memory.\n");
return -1;
}
palette[0].red = fg_color[0];
palette[0].green = fg_color[1];
palette[0].blue = fg_color[2];
palette[1].red = bg_color[0];
palette[1].green = bg_color[1];
palette[1].blue = bg_color[2];
alpha_values[0] = fg_color[3];
alpha_values[1] = bg_color[3];
png_set_PLTE(png_ptr, info_ptr, palette, 2);
png_set_tRNS(png_ptr, info_ptr, alpha_values, 2, NULL);
}
png_init_io(png_ptr, fp);
if(type == PNG_TYPE) {
png_set_IHDR(png_ptr, info_ptr,
realwidth, realwidth,
1,
PNG_COLOR_TYPE_PALETTE,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
} else {
png_set_IHDR(png_ptr, info_ptr,
realwidth, realwidth,
8,
PNG_COLOR_TYPE_RGB_ALPHA,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
}
png_set_pHYs(png_ptr, info_ptr,
dpi * INCHES_PER_METER,
dpi * INCHES_PER_METER,
PNG_RESOLUTION_METER);
png_write_info(png_ptr, info_ptr);
if(type == PNG_TYPE) {
/* top margin */
memset(row, 0xff, (realwidth + 7) / 8);
for(y = 0; y < margin * size; y++) {
png_write_row(png_ptr, row);
}
/* data */
p = qrcode->data;
for(y = 0; y < qrcode->width; y++) {
memset(row, 0xff, (realwidth + 7) / 8);
q = row;
q += margin * size / 8;
bit = 7 - (margin * size % 8);
for(x = 0; x < qrcode->width; x++) {
for(xx = 0; xx < size; xx++) {
*q ^= (*p & 1) << bit;
bit--;
if(bit < 0) {
q++;
bit = 7;
}
}
p++;
}
for(yy = 0; yy < size; yy++) {
png_write_row(png_ptr, row);
}
}
/* bottom margin */
memset(row, 0xff, (realwidth + 7) / 8);
for(y = 0; y < margin * size; y++) {
png_write_row(png_ptr, row);
}
} else {
/* top margin */
fillRow(row, realwidth, bg_color);
for(y = 0; y < margin * size; y++) {
png_write_row(png_ptr, row);
}
/* data */
p = qrcode->data;
for(y = 0; y < qrcode->width; y++) {
fillRow(row, realwidth, bg_color);
for(x = 0; x < qrcode->width; x++) {
for(xx = 0; xx < size; xx++) {
if(*p & 1) {
memcpy(&row[((margin + x) * size + xx) * 4], fg_color, 4);
}
}
p++;
}
for(yy = 0; yy < size; yy++) {
png_write_row(png_ptr, row);
}
}
/* bottom margin */
fillRow(row, realwidth, bg_color);
for(y = 0; y < margin * size; y++) {
png_write_row(png_ptr, row);
}
}
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
free(row);
free(palette);
return 0;
}
static QRcode *encode(const unsigned char *intext, int length)
{
QRcode *code;
code = QRcode_encodeString((char *)intext, version, level, hint, casesensitive);
return code;
}
static void qrencode(const unsigned char *intext, int length, const char *outfile)
{
QRcode *qrcode;
qrcode = encode(intext, length);
if(qrcode == NULL) {
if(errno == ERANGE) {
fprintf(stderr, "Failed to encode the input data: Input data too large\n");
} else {
perror("Failed to encode the input data");
}
return ;
}
writePNG(qrcode, outfile, image_type);
QRcode_free(qrcode);
}
int qrcodeString(unsigned char *string,char *path)
{
qrencode(string, strlen(string), path);
return 0;
}
<file_sep>/module/updater/CMakeLists.txt
add_definitions(-DUSE_NOR)
set(UPDATER_SRC_FILES
updater.cpp
verify/crc/crc32.cpp
verify/md5/md5sum.cpp
display/display.cpp
wget/httpd.cpp
partition/partition.cpp
)
add_executable(updater ${UPDATER_SRC_FILES})
target_include_directories(updater
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/verify/crc
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/verify/md5
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/display
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/wget
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/partition
)
<file_sep>/src/app/my_gpio.c
/*
* =====================================================================================
*
* Filename: MyGpioCtr.c
*
* Description: GPIO控制
*
* Version: 1.0
* Created: 2015-12-24 09:06:46
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
/* ----------------------------------------------------------------*
* include head files
*-----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <unistd.h>
#include "debug.h"
#include "thread_helper.h"
#include "hal_gpio.h"
#include "my_gpio.h"
/* ----------------------------------------------------------------*
* extern variables declare
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*
* internal functions declare
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define GPIO_MAX_INPUT_TASK 32
typedef struct _MyGpioTable {
int portid;
char *name;
int active; //有效值
int default_value; //默认值
int active_time;
int current_value;
int portnum;
int flash_times;
int flash_set_time;
int flash_delay_time;
int flash_even_flag;
int delay_time;
}MyGpioTable;
typedef struct _MyGpioInputTask {
int port;
void *arg;
void (* thread)(void *,int);
}MyGpioInputTask;
typedef struct _MyGpioPriv {
MyGpioTable *table;
pthread_mutex_t mutex;
int task_num;
}MyGpioPriv;
/* ----------------------------------------------------------------*
* variables define
*-----------------------------------------------------------------*/
static MyGpioTable gpio_normal_tbl[]={
{ENUM_GPIO_MICKEY, "mickey",0,IO_ACTIVE},
{ENUM_GPIO_SPKL, "spkctl",1,IO_ACTIVE},
{ENUM_GPIO_SPKR, "spkctr",1,IO_ACTIVE},
{ENUM_GPIO_KEYLED_BLUE,"keyled1",1,IO_INACTIVE},
{ENUM_GPIO_KEYLED_RED,"keyled2",1,IO_INACTIVE},
{ENUM_GPIO_IRLEDEN,"irleden",1,IO_ACTIVE},
{ENUM_GPIO_ASNKEY, "asnkey",0,IO_ACTIVE},
{ENUM_GPIO_MICEN, "micen", 0,IO_ACTIVE},
{ENUM_GPIO_SDCTRL, "sdctrl",1,IO_ACTIVE},
{ENUM_GPIO_ICRAIN, "icrain",0,IO_ACTIVE},
{ENUM_GPIO_ICBAIN, "icrbin",1,IO_ACTIVE},
};
MyGpio *gpio = NULL;
/* ---------------------------------------------------------------------------*/
/**
* @brief myGpioSetValue GPIO口输出赋值,不立即执行
*
* @param This
* @param port IO口
* @param Value 有效IO_ACTIVE or 无效IO_INACTIVE
*/
/* ---------------------------------------------------------------------------*/
static int myGpioSetValue(MyGpio *This,int port,int Value)
{
MyGpioTable *table;
table = This->priv->table+port;
#ifdef X86
if (table->default_value == IO_NO_EXIST ) { //输出
#else
if ( (table->default_value == IO_INPUT)
|| (table->default_value == IO_NO_EXIST) ) { //输出
#endif
// printf("[%d]set value fail,it is input or not exist!\n",port);
return 0;
}
if (Value == IO_ACTIVE) {
table->current_value = table->active;
} else {
table->current_value = !(table->active);
}
return 1;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myGpioSetValueNow GPIO口输出赋值,并立即执行
*
* @param This
* @param port IO口
* @param Value 有效IO_ACTIVE or 无效IO_INACTIVE
*/
/* ---------------------------------------------------------------------------*/
static void myGpioSetValueNow(MyGpio *This,int port,int Value)
{
MyGpioTable *table;
table = This->priv->table+port;
if (myGpioSetValue(This,port,Value) == 0)
return;
pthread_mutex_lock(&This->priv->mutex);
if (table->current_value)
halGpioOut(table->portid,table->name,1);
else
halGpioOut(table->portid,table->name,0);
pthread_mutex_unlock(&This->priv->mutex);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myGpioRead 读输入口的值
*
* @param This
* @param port IO口
*
* @returns 真正的值 0或1
*/
/* ---------------------------------------------------------------------------*/
static int myGpioRead(MyGpio *This,int port)
{
MyGpioTable *table;
table = This->priv->table+port;
if (table->default_value != IO_INPUT) {
goto return_value;
}
#ifndef X86
if (halGpioIn(table->portid,table->name))
table->current_value = 1;
else
table->current_value = 0;
#endif
return_value:
return table->current_value;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myGpioIsActive 读取输入IO值,并判断是否IO有效
*
* @param This
* @param port IO口
*
* @returns 有效IO_ACTIVE or 无效IO_INACTIVE
*/
/* ---------------------------------------------------------------------------*/
static int myGpioIsActive(MyGpio *This,int port)
{
MyGpioTable *table;
table = This->priv->table+port;
if (table->default_value == IO_NO_EXIST) {
return IO_NO_EXIST;
}
if (myGpioRead(This,port) == table->active){
return IO_ACTIVE;
} else {
return IO_INACTIVE;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myGpioFlashTimer GPIO闪烁执行函数,在单独的定时线程中执行
* IO口电平变化到还原算一次
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void myGpioFlashTimer(MyGpio *This)
{
int i;
MyGpioTable *table;
table = This->priv->table;
for (i=0; i<This->io_num; i++) {
if (table->default_value == IO_NO_EXIST) {
table++;
continue;
}
if (table->default_value == IO_INPUT) {
table++;
continue;
}
if ((table->flash_delay_time == 0) || (table->flash_times == 0)) {
table++;
continue;
}
if (--table->flash_delay_time == 0) {
table->flash_even_flag++;
if (table->flash_even_flag == 2) { //亮灭算一次
table->flash_times--;
table->flash_even_flag = 0;
}
table->flash_delay_time = table->flash_set_time;
if (myGpioIsActive(This,i) == IO_ACTIVE)
myGpioSetValueNow(This,i,IO_INACTIVE);
else
myGpioSetValueNow(This,i,IO_ACTIVE);
}
table++;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myGpioFlashStart 设置GPIO闪烁,并执行
*
* @param This
* @param port IO口
* @param freq 频率 根据myGpioFlashTimer 执行时间决定
* @param times 闪烁总次数 FLASH_FOREVER为循环闪烁
*/
/* ---------------------------------------------------------------------------*/
static void myGpioFlashStart(MyGpio *This,int port,int freq,int times)
{
MyGpioTable *table;
table = This->priv->table+port;
if (table->default_value == IO_NO_EXIST) {
return;
}
if (table->flash_set_time != freq) {
table->flash_delay_time = freq;
table->flash_set_time = freq;
table->flash_times = times;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myGpioFlashStop GPIO停止闪烁
*
* @param This
* @param port IO口
*/
/* ---------------------------------------------------------------------------*/
static void myGpioFlashStop(MyGpio *This,int port)
{
MyGpioTable *table;
table = This->priv->table+port;
if (table->default_value == IO_NO_EXIST) {
return;
}
table->flash_delay_time = 0;
table->flash_set_time = FLASH_STOP;
table->flash_times = 0;
table->flash_even_flag = 0;
myGpioSetValue(This,port,IO_INACTIVE);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myGpioSetActiveTime 设置输入IO口的有效电平时间
*
* @param This
* @param port IO口
* @param value 时间
*/
/* ---------------------------------------------------------------------------*/
static void myGpioSetActiveTime(struct _MyGpio *This,int port,int value)
{
MyGpioTable *table;
table = This->priv->table+port;
if (table->default_value != IO_INPUT) {
return;
}
table->active_time = value;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myGpioInputHandle 检测输入IO电平
*
* @param This
* @param port
*
* @returns 1为有效 0为无效
*/
/* ---------------------------------------------------------------------------*/
static int myGpioInputHandle(struct _MyGpio *This,int port)
{
MyGpioTable *table;
table = This->priv->table+port;
int ret = myGpioIsActive(This,port);
// printf("port:%d,ret:%d,delay_time:%d\n",
// port,ret,table->delay_time );
if (ret != IO_ACTIVE) {
table->delay_time = 0;
return 0;
}
if (table->delay_time < table->active_time) {
++table->delay_time;
return 0;
} else {
return 1;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myGpioInit GPIO初始化,在创建IO对象后必须执行
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void myGpioInit(MyGpio *This)
{
int i;
MyGpioTable *table;
table = This->priv->table;
for (i=0; i<This->io_num; i++) {
if (table->portid < 0) // 可以在配置文件将不用IO写-1
table->default_value = IO_NO_EXIST;
if (table->default_value == IO_NO_EXIST) {
table++;
continue;
}
if (table->default_value != IO_INPUT) {
halGpioSetMode(table->portid,table->name,HAL_OUTPUT);
} else {
halGpioSetMode(table->portid,table->name,HAL_INPUT);
}
if (table->default_value != IO_INPUT)//设置默认值
myGpioSetValueNow(This,i,table->default_value);
table->flash_delay_time = 0;
table->flash_set_time = FLASH_STOP;
table->flash_times = 0;
table->flash_even_flag = 0;
table++;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myGpioDestroy 销毁GPIO对象
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void myGpioDestroy(MyGpio *This)
{
free(This->priv);
free(This);
This = NULL;
}
/* ----------------------------------------------------------------*/
/**
* @brief myGpioHandle GPIO输出执行函数,真正对IO口赋值,在单独线程
* 中执行,IO输出以脉冲形式,防止非正常情况导致IO口电平一时错误
*
* @param this
*/
/* ---------------------------------------------------------------------------*/
static void myGpioHandle(MyGpio *This)
{
int i;
MyGpioTable *table;
table = This->priv->table;
for (i=0; i<This->io_num; i++) {
if (table->default_value == IO_NO_EXIST) {
table++;
continue;
}
if (table->default_value == IO_INPUT) {
table++;
continue;
}
if (table->current_value)
halGpioOut(table->portid,table->name,1);
else
halGpioOut(table->portid,table->name,0);
table++;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myGpioThread Gpio处理函数,50ms处理一次
*
* @param arg
*/
/* ---------------------------------------------------------------------------*/
static void * myGpioOutputThread(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
MyGpio *This = arg;
while (This != NULL) {
myGpioHandle(This);
myGpioFlashTimer(This);
usleep(50000);// 50ms
}
return NULL;
}
static void myGpioAddInputThread(MyGpio *This,
struct GpioArgs *args,
void *(* thread)(void *))
{
createThread(thread,args);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myGpioPrivCreate 创建GPIO对象
*
* @param gpio_table GPIO列表
*
* @returns GPIO对象
*/
/* ---------------------------------------------------------------------------*/
MyGpio* myGpioPrivCreate(MyGpioTable *gpio_table,int io_num)
{
MyGpio *This = (MyGpio *)calloc(1,sizeof(MyGpio));
This->priv = (MyGpioPriv *)calloc(1,sizeof(MyGpioPriv));
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&This->priv->mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
This->priv->table = gpio_table;
This->io_num = io_num;
This->SetValue = myGpioSetValue;
This->SetValueNow = myGpioSetValueNow;
This->FlashStart = myGpioFlashStart;
This->FlashStop = myGpioFlashStop;
This->Destroy = myGpioDestroy;
This->IsActive = myGpioIsActive;
This->setActiveTime = myGpioSetActiveTime;
This->inputHandle = myGpioInputHandle;
This->addInputThread = myGpioAddInputThread;
myGpioInit(This);
createThread(myGpioOutputThread,This);
return This;
}
void gpioInit(void)
{
DPRINT("gpio init\n");
gpio = myGpioPrivCreate(gpio_normal_tbl,
sizeof(gpio_normal_tbl) / sizeof(MyGpioTable));
}
void gpioTalkDirOut(void)
{
if (!gpio)
return;
gpio->SetValue(gpio,ENUM_GPIO_MICKEY,IO_INACTIVE);
gpio->SetValue(gpio,ENUM_GPIO_SPKL,IO_INACTIVE);
gpio->SetValue(gpio,ENUM_GPIO_SPKR,IO_ACTIVE);
gpio->SetValue(gpio,ENUM_GPIO_ASNKEY,IO_INACTIVE);
}
void gpioTalkDirIn(void)
{
if (!gpio)
return;
gpio->SetValue(gpio,ENUM_GPIO_MICKEY,IO_ACTIVE);
gpio->SetValue(gpio,ENUM_GPIO_SPKL,IO_ACTIVE);
gpio->SetValue(gpio,ENUM_GPIO_SPKR,IO_INACTIVE);
gpio->SetValue(gpio,ENUM_GPIO_ASNKEY,IO_ACTIVE);
}
void gpioChargeState(int state)
{
if (!gpio)
return;
if (state) {
gpio->FlashStop(gpio,ENUM_GPIO_KEYLED_RED);
gpio->SetValue(gpio,ENUM_GPIO_KEYLED_BLUE,IO_ACTIVE);
gpio->SetValue(gpio,ENUM_GPIO_KEYLED_RED,IO_INACTIVE);
} else {
gpio->SetValue(gpio,ENUM_GPIO_KEYLED_BLUE,IO_INACTIVE);
}
}
void gpioLowPowerState(int state)
{
if (!gpio)
return;
if (state) {
gpio->FlashStart(gpio,ENUM_GPIO_KEYLED_RED,FLASH_SLOW,FLASH_FOREVER);
} else {
gpio->FlashStop(gpio,ENUM_GPIO_KEYLED_RED);
gpio->SetValue(gpio,ENUM_GPIO_KEYLED_RED,IO_INACTIVE);
}
}
<file_sep>/src/app/udp_talk/udp_talk_transport.c
/*
* =============================================================================
*
* Filename: Rtp.c
*
* Description: 传输处理
*
* Version: 1.0
* Created: 2016-03-01 14:27:57
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/timeb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/ipc.h>
#include <sys/socket.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
#include <errno.h>
#include <linux/fb.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/un.h>
#include <signal.h>
#include <sys/time.h>
#include <dirent.h>
#include <pthread.h>
#include <sys/prctl.h>
#include "udp_server.h"
#include "udp_talk_protocol.h"
#include "udp_talk_transport.h"
#include "udp_talk_parse.h"
#include "share_memory.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_RTP > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define AUDIO_SIZE 1024
#define LOADFUNC(func) \
do {\
if (in->func)\
priv->func = in->func;\
} while (0)
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
Rtp * udp_talk_trans = NULL;
static uint8_t RTPTerminate; //RTP线程是否结束
static uint8_t SPITerminate; //SPI线程是否结束
static uint8_t RTPThreadExit; //RTP线程是否结束
static uint8_t SPIThreadExit; //SPI线程是否结束
static TRTPObject *RTPObject = NULL; //RTP传输对象
static PShareMemory RtpDcMem; //RTP与Dc的共享内存
// 打印帧率
int seq = 0;
int cnt_test = 0;
static pthread_t RTP_pthread;
static pthread_t Encode_pthread;
static pthread_t SPI_pthread;
static void *call_back_data;
static int last_i_seq = 0;
static int last_seq = 0;
static int isIframe(unsigned char *sdata)
{
if ( (sdata[0] == 0x00)
&& (sdata[1] == 0x00)
&& (sdata[2] == 0x00)
&& (sdata[3] == 0x01)
&& ( (sdata[4] == 0x65) || (sdata[4] == 0x67)
|| (sdata[4] == 0x25) || (sdata[4] == 0x27)) ) {
return 1;
} else if ((sdata[0] == 0x00)
&& (sdata[1] == 0x00)
&& (sdata[2] == 0x01)
&& ( (sdata[3] == 0x65) || (sdata[3] == 0x67)
|| (sdata[3] == 0x25) || (sdata[3] == 0x27)) ) {
return 1;
}
return 0;
}
static int needDecode(int cur_seq,unsigned char *sdata)
{
//关键帧,需要解码
if (isIframe(sdata)) {
last_i_seq = cur_seq;
last_seq = cur_seq;
return 1;
}
if(cur_seq == (last_seq + 1)) {
last_seq = cur_seq;
return 1;
}
printf("loss seq:%d last_seq:%d last_i_seq:%d\n",cur_seq,last_seq,last_i_seq);
return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief decodeAudio 解码音频
*
* @param This
* @param pbody 音频数据结构
*/
/* ---------------------------------------------------------------------------*/
static void decodeAudio(Rtp* This,rec_body *pbody)
{
//处理音频
if(pbody->alen <= 0 || pbody->alen >= 12000) { //保存远程衰减强度
printf("Error! pbody->alen:%d\n",pbody->alen);
return;
}
if (This->silence == FALSE) {
if (This->interface->receiveAudio)
This->interface->receiveAudio(This,pbody->sdata,pbody->alen);
}
}
static void decodeVideo(Rtp* This,rec_body *pbody,int size)
{
char *pBuf = NULL;
if(RtpDcMem)
pBuf = RtpDcMem->SaveStart(RtpDcMem);//取缓冲区用于储存
if(pBuf)
memcpy(pBuf,pbody,size);
if(RtpDcMem)
RtpDcMem->SaveEnd(RtpDcMem,size);
}
static int rtpGetVideo(Rtp* This,void *data)
{
rec_body *pbody = NULL;
int size = 0;
if (RtpDcMem == NULL)
return 0;
if (RtpDcMem->WriteCnt(RtpDcMem) <= 0)
return 0;
pbody = (rec_body *)RtpDcMem->GetStart(RtpDcMem,&size);
if (!pbody || size == 0) {
return 0;
}
if (pbody->slen == 0) {
RtpDcMem->GetEnd(RtpDcMem);
return 0;
}
if(needDecode(pbody->seq,pbody->sdata) == 0) {
RtpDcMem->GetEnd(RtpDcMem);
return 0;
}
memcpy(data,pbody->sdata,pbody->slen);
RtpDcMem->GetEnd(RtpDcMem);
return pbody->slen;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rtpThreadExecute RTP线程,接收音频,视频数据
*
* @param ThreadData
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static void * rtpThreadExecute(void *ThreadData)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
Rtp* This = (Rtp*)ThreadData;
char *pData;
int Size=0;
pData = (char*)malloc(sizeof(rec_body));
if(pData == NULL) {
printf("Can't alloc memory!\n");
RTPThreadExit = TRUE;
pthread_exit(NULL);
return NULL;
}
while(!RTPTerminate) {
memset(pData,0,sizeof(rec_body));
if(RTPObject != NULL) {
Size = RTPObject->RecvBuffer(RTPObject,pData,sizeof(rec_body),500);
}
if(Size == -1) {
//对方已关闭连接
printf("RTP receive is abort!\n");
if(RtpDcMem) {
RtpDcMem->SaveEnd(RtpDcMem,0);
}
if (This->interface->abortCallBack)
This->interface->abortCallBack(This);
break;
} else if(Size > 0) {
rec_body *pbody = (rec_body*)pData;
if(pbody->alen > 0) { //解码音频
decodeAudio(This,pbody);
} else if (pbody->slen > 0){
decodeVideo(This,pbody,Size);
}
}
usleep(1000);
}
if (This->interface->receiveEnd)
This->interface->receiveEnd(This);
free(pData);
pData = NULL;
RTPThreadExit = TRUE;
pthread_exit(NULL);
return NULL;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rtpThreadCreate 创建RTP线程
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void rtpThreadCreate(Rtp* This)
{
int result;
struct sched_param SchedParam; //优先级
pthread_attr_t threadAttr1; //线程属性
RTPTerminate = FALSE;
RTPThreadExit = FALSE;
pthread_attr_init(&threadAttr1); //附加参数
SchedParam.sched_priority = 3;
pthread_attr_setschedparam(&threadAttr1, &SchedParam);
pthread_attr_setdetachstate(&threadAttr1,PTHREAD_CREATE_DETACHED); //设置线程为自动销毁
result = pthread_create(&RTP_pthread,&threadAttr1,rtpThreadExecute,This);
if(result) {
RTPThreadExit = TRUE;
printf("rtpThreadCreate() pthread failt,Error code:%d\n",result);
}
pthread_attr_destroy(&threadAttr1); //释放附加参数
}
/* ---------------------------------------------------------------------------*/
/**
* @brief spiAudio 发送音频
*
* @param This
* @param pAudioPack
*
* @returns 0失败 1成功
*/
/* ---------------------------------------------------------------------------*/
static int spiAudio(Rtp* This,
rec_body *pAudioPack)
{
if(This->bTransAudio == 0 || !pAudioPack) {
return 0;
}
int packsize = 0;
short AudioBuf[AUDIO_SIZE];
if (This->interface->sendAudio)
packsize = This->interface->sendAudio(This,AudioBuf,AUDIO_SIZE);
if(packsize <= 0) {
return 1;
}
pAudioPack->seq++;
pAudioPack->vtype = 0;
pAudioPack->slen = 0;
memcpy(pAudioPack->sdata, AudioBuf, packsize);
pAudioPack->alen = packsize;
pAudioPack->tlen = RECHEADSIZE+pAudioPack->alen;
if(RTPObject) {
// if ( (short)(pAudioPack->sdata[1] * 256 + pAudioPack->sdata[0]) > 6024
// || (short)(pAudioPack->sdata[1] * 256 + pAudioPack->sdata[0]) < -1024 ) {
// printf("--------------------------------------->get voice!!!\n");
// udp_server->SendBuffer(udp_server,"172.16.100.102",1221, //返回信息
// (char *)&pAudioPack,pAudioPack->tlen);
// }
RTPObject->SendBuffer(RTPObject,pAudioPack,pAudioPack->tlen);
}
return 1;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief spiHeart 没有音频发送时发送心跳包
*
* @param pAudioPack
*/
/* ---------------------------------------------------------------------------*/
static void spiHeart(rec_body *pAudioPack)
{
pAudioPack->seq = 0;
pAudioPack->vtype = 0;
pAudioPack->slen = 0;
pAudioPack->alen = 0;
pAudioPack->tlen = RECHEADSIZE+pAudioPack->alen+32;
if(RTPObject) {
RTPObject->SendBuffer(RTPObject,pAudioPack,pAudioPack->tlen);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief spiThreadExecute 执行SPI,发送音频和视频
*
* @param ThreadData
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static void * spiThreadExecute(void *ThreadData)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
Rtp* This = (Rtp*)ThreadData;
rec_body *pAudioPack = (rec_body*)malloc(sizeof(rec_body));
seq=0;
// 帧率 fps
while(!SPITerminate) {
if (spiAudio(This,pAudioPack) == 0) {
spiHeart(pAudioPack);
sleep(1);
continue;
}
usleep(10000);
}
seq = 0;
cnt_test = 0;
if (This->interface->sendEnd)
This->interface->sendEnd(This);
if(pAudioPack)
free(pAudioPack);
pAudioPack = NULL;
SPIThreadExit = TRUE;
pthread_exit(NULL);
return NULL;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief spiThreadCreate 创建SPI线程
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void spiThreadCreate(Rtp* This)
{
int result;
pthread_attr_t threadAttr1; //线程属性
struct sched_param SchedParam; //优先级
SPITerminate = FALSE;
SPIThreadExit = FALSE;
SchedParam.sched_priority = 6;
pthread_attr_init(&threadAttr1);
pthread_attr_setdetachstate(&threadAttr1,PTHREAD_CREATE_DETACHED); //设置线程为自动销毁
result = pthread_create(&SPI_pthread,&threadAttr1,spiThreadExecute,This);
if(result) {
SPIThreadExit = TRUE;
printf("spiThreadCreate() pthread failt,Error code:%d\n",result);
}
pthread_attr_destroy(&threadAttr1); //释放附加参数
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rtpInit 初始化RTP连接
*
* @param This
* @param IP 呼叫IP
* @param Port
*
* @returns CALL_FAIL 失败 CALL_OK 成功
*/
/* ---------------------------------------------------------------------------*/
static int rtpInit(Rtp *This, const char *dest_ip, int Port)
{
if(RTPObject == NULL) {
RTPObject = TRTPObject_Create(dest_ip,Port);
}
if(RTPObject == NULL) {
return CALL_FAIL;
}
return CALL_OK;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rtpBuildConnect 建立RTP连接
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void rtpBuildConnect(Rtp *This)
{
This->fpAudio = -1;
This->bTransAudio = FALSE;
This->bTransVideo = TRUE;
if (This->interface->start)
This->interface->start(This);
if(RtpDcMem==NULL)
RtpDcMem = CreateShareMemory(sizeof(rec_body),2,0);
last_i_seq = 0;
last_seq = 0;
rtpThreadCreate(This);
spiThreadCreate(This);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rtpStartAudio 使能传输音频
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void rtpStartAudio(Rtp *This)
{
This->bTransAudio = TRUE;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rtpGetFpAudio 返回通话音频句柄地址
*
* @param This
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int *rtpGetFpAudio(Rtp *This)
{
return &This->fpAudio;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rtpSetSilence 设置通话时本地是否静音,
* 用于通话时同时播放MP3情况
*
* @param This
* @param value TRUE 静音 FALSE 非静音
*/
/* ---------------------------------------------------------------------------*/
static void rtpSetSilence(Rtp *This,int value)
{
This->silence = value;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rtpGetSilence 获得当前静音状态
*
* @param This
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int rtpGetSilence(Rtp *This)
{
return This->silence;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rtpSetPeerIp 设置通讯IP
*
* @param This
* @param ip
*/
/* ---------------------------------------------------------------------------*/
static int rtpSetPeerIp(Rtp *This,char *ip)
{
if (!RTPObject)
return FALSE;
strncpy(RTPObject->cPeerIP,ip,15);
RTPObject->dwPeerIP = inet_addr(ip);
return TRUE;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief rtpClose 通话结束,关闭RTP线程
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void rtpClose(Rtp *This)
{
This->silence = FALSE;
This->bTransAudio = FALSE;
This->bTransVideo = FALSE;
printf("Wait RTPThreadExit\n");
RTPTerminate = TRUE;
while(!RTPThreadExit) {usleep(10000);}
if(RtpDcMem) {
RtpDcMem->CloseMemory(RtpDcMem);
}
printf("Wait SPIThreadExit\n");
SPITerminate = TRUE;
while(!SPIThreadExit) {usleep(10000);}
if(RtpDcMem) {
RtpDcMem->Destroy(RtpDcMem);
RtpDcMem = NULL;
}
if(RTPObject) {
RTPObject->Destroy(RTPObject); //bug maybe ---Jack
RTPObject = NULL;
}
printf("[%s]\n", __func__);
}
static void rtpDestroy(Rtp **This)
{
free(*This);
*This = NULL;
}
static void loadInterface(UdpTalkTransInterface *priv,UdpTalkTransInterface *in)
{
LOADFUNC(abortCallBack);
LOADFUNC(start);
LOADFUNC(receiveAudio);
LOADFUNC(receiveEnd);
LOADFUNC(sendStart);
LOADFUNC(sendVideo);
LOADFUNC(sendAudio);
LOADFUNC(sendEnd);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief createRtp 创建RTP传输对象
*
* @param h264_type_tmp 视频分辨率结构
* @param abortCallBack 视频中断时回调函数
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
Rtp * createRtp(UdpTalkTransInterface *interface,void *callBackData)
{
Rtp * This = (Rtp *)calloc(1,sizeof(Rtp));
This->interface = (UdpTalkTransInterface *)calloc(1,sizeof(UdpTalkTransInterface));
SPIThreadExit = TRUE;
RTPThreadExit = TRUE;
call_back_data = callBackData;
loadInterface(This->interface,interface);
This->getFpAudio = rtpGetFpAudio;
This->setSilence = rtpSetSilence;
This->getSilence = rtpGetSilence;
This->setPeerIp = rtpSetPeerIp;
This->getVideo = rtpGetVideo;
This->init = rtpInit;
This->buildConnect = rtpBuildConnect;
This->startAudio = rtpStartAudio;
This->close = rtpClose;
This->Destroy = rtpDestroy;
return This;
}
<file_sep>/src/app/video/camera/camera_factory.h
#ifndef __CAMERA_FACTORY_H_
#define __CAMERA_FACTORY_H_
#include <CameraHal/CamHwItf.h>
#include <CameraHal/CamCifDevHwItf.h>
#include <CameraHal/cam_types.h>
#include <CameraHal/IonCameraBuffer.h>
class CameraFactory final {
public:
CameraFactory() {}
virtual ~CameraFactory() {}
shared_ptr<CamHwItf> GetCamHwItf(struct rk_cams_dev_info* cam_info, const int index)
{
shared_ptr<CamHwItf> dev;
if (cam_info->cam[index]->type == RK_CAM_ATTACHED_TO_ISP)
{
dev = getCamHwItf(&cam_info->isp_dev);
}
else if (cam_info->cam[index]->type == RK_CAM_ATTACHED_TO_CIF)
{
int cif_index = ((struct rk_cif_dev_info*)(cam_info->cam[index]->dev))->cif_index;
dev = shared_ptr<CamHwItf>(new CamCifDevHwItf(&(cam_info->cif_devs.cif_devs[cif_index])));
}
else
{
return NULL;
}
return dev;
}
};
#endif // __CAMERA_FACTORY_H_
<file_sep>/src/app/my_update.c
/*
* =============================================================================
*
* Filename: my_update.c
*
* Description: 升级流程
*
* Version: 1.0
* Created: 2019-09-03 14:19:57
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include "iniparser/iniparser.h"
#include "thread_helper.h"
#include "externfunc.h"
#include "my_update.h"
#include "my_http.h"
#include "remotefile.h"
#include "config.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define SIZE_CONFIG(x) x,sizeof(x) - 1
#define NELEMENTS(array) (sizeof (array) / sizeof ((array) [0]))
struct VersionType{
int major; // 主版本,区分设备类型及方案平台
int minor; // 次版本,有功能更新时增加
int release; // 发布版本,修改bug时增加
};
typedef struct _UpdateFileInfo {
char dev_type[64]; // 设备类型
char version[16]; // 升级包软件版本
char start_version[16]; // 升级包升级软件起始版本
char end_version[16]; // 升级包升级软件结束版本
char force[8]; // 是否强制升级,0否 1是
char url[128]; // 升级包地址
char readme[256]; // 升级内容
int need_update; // 是否需要升级,0不需要,1需要,强制升级时,直接进入升级界面
} UpdateFileInfo;
struct _MyUpdatePrivate {
char ip[16];
char file_path[512];
int port;
int type;
int check_update;
int is_updating;
TRemoteFile * remote;
UpdateFunc callbackFunc;
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
MyUpdate *my_update = NULL;
static MyHttp *http = NULL;
static UpdateFileInfo update_info;
static dictionary* update_ini = NULL;
static EtcValueChar etc_update_char[]={
{"VersionInfo", "DevType", SIZE_CONFIG(update_info.dev_type), "0"},
{"VersionInfo", "Version", SIZE_CONFIG(update_info.version), "0"},
{"VersionInfo", "StartVersion", SIZE_CONFIG(update_info.start_version), "0"},
{"VersionInfo", "EndVersion", SIZE_CONFIG(update_info.end_version), "0"},
{"VersionInfo", "Force", SIZE_CONFIG(update_info.force), "0"},
{"VersionInfo", "Url", SIZE_CONFIG(update_info.url), "0"},
{"VersionInfo", "Readme", SIZE_CONFIG(update_info.readme), "0"},
};
/* ---------------------------------------------------------------------------*/
/**
* @brief tarUpdateFiles
* 解压升级包
* 判断升级包完整新
* 执行升级
* 退出程序重启
*/
/* ---------------------------------------------------------------------------*/
static void tarUpdateFiles(int type,char *s_path,char *d_path,char *update_file_name)
{
char update_buf[64] = {0};
char update_go_buf[64] = {0};
// SD卡升级,必须退出主程序,否则内存不足
if (type == UPDATE_TYPE_SDCARD){
if (my_update->interface->uiUpdateSdCard)
my_update->interface->uiUpdateSdCard();
sleep(1);
exit(1);
}
sprintf(update_buf,"tar xzf %s%s -C %s",s_path,update_file_name,d_path);
int ret = system(update_buf);
sprintf(update_go_buf,"%supdate/go.sh",d_path);
if (ret == 0 && fileexists(update_go_buf)) {
system(update_go_buf);
if (my_update->interface->uiUpdateSuccess)
my_update->interface->uiUpdateSuccess();
sync();
sleep(1);
exit(0);
} else {
if (my_update->interface->uiUpdateFail)
my_update->interface->uiUpdateFail();
}
}
static int init(struct _MyUpdate * This,int type,char *ip,int port,char *file_path,UpdateFunc callbackFunc)
{
This->priv->type = type;
This->priv->callbackFunc = callbackFunc;
if (This->priv->type == UPDATE_TYPE_CENTER) {
This->priv->port = port;
if (ip)
strcpy(This->priv->ip,ip);
if (file_path)
strcpy(This->priv->file_path,file_path);
This->priv->remote = CreateRemoteFile(ip,"Update1.cab");
}
return 0;
}
static int download(struct _MyUpdate *This)
{
if (This->priv->type == UPDATE_TYPE_CENTER) {
This->priv->remote->Download(This->priv->remote,
0,This->priv->file_path,UPDATE_INI_PATH UPDATE_APP,FALSE,This->priv->callbackFunc);
tarUpdateFiles(This->priv->type,UPDATE_INI_PATH,UPDATE_INI_PATH,UPDATE_APP);
} else if (This->priv->type == UPDATE_TYPE_SDCARD) {
tarUpdateFiles(This->priv->type,SDCARD_PATH,UPDATE_INI_PATH,UPDATE_IMG);
} else if (This->priv->type == UPDATE_TYPE_SERVER) {
int leng = 0;
if (update_info.url[0]) {
leng = http->download(update_info.url,NULL,UPDATE_INI_PATH UPDATE_APP,This->priv->callbackFunc);
tarUpdateFiles(This->priv->type,UPDATE_INI_PATH,UPDATE_INI_PATH,UPDATE_APP);
}
}
return 0;
}
static int uninit(struct _MyUpdate *This)
{
if (This->priv->type == UPDATE_TYPE_CENTER) {
if (This->priv->remote)
This->priv->remote->Destroy(This->priv->remote);
} else if (This->priv->type == UPDATE_TYPE_SDCARD) {
} else if (This->priv->type == UPDATE_TYPE_SERVER) {
}
return 0;
}
static int loadIniFile(dictionary **d,char *file_path,char *sec[])
{
int ret = 0;
int i;
*d = iniparser_load(file_path);
if (*d == NULL) {
*d = dictionary_new(0);
assert(*d);
ret++;
for (i=0; sec[i] != NULL; i++)
iniparser_set(*d, sec[i], NULL);
} else {
int nsec = iniparser_getnsec(*d);
int j;
const char * secname;
for (i=0; sec[i] != NULL; i++) {
for (j=0; j<nsec; j++) {
secname = iniparser_getsecname(*d, j);
if (strcasecmp(secname,sec[i]) == 0)
break;
}
if (j == nsec) {
ret++;
iniparser_set(*d, sec[i], NULL);
}
}
}
return ret;
}
static void* threadCheckUpdatInfo(void *arg)
{
http = myHttpCreate();
memset(&update_info,0,sizeof(UpdateFileInfo));
int check_tick = 10; // 启动等待UI10秒后拉取升级数据
while (1) {
if (my_update->priv->check_update == 0 && check_tick) {
check_tick--;
sleep(1);
continue;
}
int leng = http->download(UPDATE_URL,NULL,UPDATE_INI,NULL);
if (leng <= 0) {
sleep(60);
continue;
} else {
char *sec_private[] = {"VersionInfo",NULL};
my_update->priv->check_update = 0;
loadIniFile(&update_ini,UPDATE_INI,sec_private);
if (update_ini) {
configLoadEtcChar(update_ini,etc_update_char,NELEMENTS(etc_update_char));
printf("url:%s\n", update_info.url);
// 判断是否为同一型号产品
if (strcmp(DEVICE_TYPE,update_info.dev_type))
break;
struct VersionType ver_start,ver_end,ver_now;
getVersionInfo(update_info.start_version,&ver_start.major,&ver_start.minor,&ver_start.release);
getVersionInfo(update_info.end_version,&ver_end.major,&ver_end.minor,&ver_end.release);
getVersionInfo(DEVICE_SVERSION,&ver_now.major,&ver_now.minor,&ver_now.release);
// 判断当前版本是否在要升级的软件版本范围之内
if (ver_now.major != ver_start.major || ver_now.major != ver_end.major)
break;
int start_ver_int = ver_start.minor * 10 + ver_start.release;
int end_ver_int = ver_end.minor * 10 + ver_end.release;
int now_ver_int = ver_now.minor * 10 + ver_now.release;
if (now_ver_int < start_ver_int || now_ver_int > end_ver_int)
break;
// 判断是否要强制升级
if (atoi(update_info.force) == 1) {
myUpdateStart(UPDATE_TYPE_SERVER,NULL,0,NULL);
} else
update_info.need_update = UPDATE_TYPE_SERVER;
}
break;
}
}
return NULL;
}
static int needUpdate(struct _MyUpdate *This,char *version,char *content)
{
This->priv->check_update = 1;
if (fileexists(SDCARD_PATH UPDATE_IMG)) {
if (version)
sprintf(version,"固件升级");
if (content)
sprintf(content,"请保证电池电量>20%%,并点击\"本地升级\"");
return UPDATE_TYPE_SDCARD;
}
if (update_info.need_update == UPDATE_TYPE_NONE)
goto need_update_out;
if (version) {
strcpy(version,update_info.version);
}
if (content) {
strcpy(content,update_info.readme);
}
need_update_out:
return update_info.need_update;
}
static int isUpdating(struct _MyUpdate *This)
{
return This->priv->is_updating;
}
void myUpdateInit(void)
{
my_update = (MyUpdate *) calloc (1,sizeof(MyUpdate));
my_update->priv =(struct _MyUpdatePrivate *) calloc (1,sizeof(struct _MyUpdatePrivate));
my_update->interface =(MyUpdateInterface *) calloc (1,sizeof(MyUpdateInterface));
my_update->init = init;
my_update->download = download;
my_update->uninit = uninit;
my_update->needUpdate = needUpdate;
my_update->isUpdating = isUpdating;
createThread(threadCheckUpdatInfo,NULL);
}
static void updateCallback(int result,int reason)
{
switch(result)
{
case UPDATE_FAIL:
if (my_update->interface->uiUpdateFail)
my_update->interface->uiUpdateFail();
break;
case UPDATE_SUCCESS:
if (my_update->interface->uiUpdateDownloadSuccess)
my_update->interface->uiUpdateDownloadSuccess();
break;
case UPDATE_POSITION:
if (my_update->interface->uiUpdatePos)
my_update->interface->uiUpdatePos(reason);
break;
default:
break;
}
}
static void * threadUpdate(void *arg)
{
my_update->priv->is_updating = 1;
if (my_update->interface->uiUpdateStart)
my_update->interface->uiUpdateStart();
my_update->download(my_update);
my_update->uninit(my_update);
if (my_update->interface->uiUpdateStop)
my_update->interface->uiUpdateStop();
my_update->priv->is_updating = 0;
return NULL;
}
void myUpdateStart(int type,char *ip,int port,char *file_path)
{
if (my_update == NULL)
return;
my_update->init(my_update,type,ip,port,file_path,updateCallback);
createThread(threadUpdate,NULL);
}
<file_sep>/src/gui/form_password.c
/*
* =============================================================================
*
* Filename: form_Password.c
*
* Description: 密码输入界面
*
* Version: 1.0
* Created: 2018-03-01 23:32:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include "externfunc.h"
#include "screen.h"
#include "my_button.h"
#include "my_title.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formPasswordProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void buttonNotify(HWND hwnd, int id, int nc, DWORD add_data);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_SET_LOCAL > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define BMP_LOCAL_PATH "setting/"
enum {
FOMR_TYPE_PASSWORD,
FOMR_TYPE_ACCOUNT,
};
enum {
IDC_TIMER_1S = IDC_FORM_PASSWORD_STATR,
IDC_BUTTON_WIFI,
IDC_EDIT_PASSWORD,
IDC_TITLE,
};
struct Keyboards {
char *func[3];
int state;
RECT rc;
BITMAP *bmp_nor;
BITMAP *bmp_pre;
};
struct KeyboardsData {
int click_x,click_y;
int index;
int key_type;
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static BITMAP bmp_key_nor;
static BITMAP bmp_key_pre;
static BITMAP bmp_key_delete_nor;
static BITMAP bmp_key_delete_pre;
static BITMAP bmp_key_abc_nor;
static BITMAP bmp_key_abc_pre;
static int bmp_load_finished = 0;
static int flag_timer_stop = 0;
struct KeyboardsData kb_data;
static int re_paint_abc = 0;
static int form_password_type = FOMR_TYPE_PASSWORD;
static char g_account[64] = {0};
static void (*getPasswordProc)(char *account,char *password);
static BmpLocation bmp_load[] = {
{&bmp_key_nor,BMP_LOCAL_PATH"Key 1.png"},
{&bmp_key_pre,BMP_LOCAL_PATH"Key 6_pre.png"},
{&bmp_key_delete_nor,BMP_LOCAL_PATH"Key 删除.png"},
{&bmp_key_delete_pre,BMP_LOCAL_PATH"Key 删除_pre.png"},
{&bmp_key_abc_nor,BMP_LOCAL_PATH"Key abc_1.png"},
{&bmp_key_abc_pre,BMP_LOCAL_PATH"Key abc_1_pre.png"},
{NULL},
};
static MY_CTRLDATA ChildCtrls [] = {
EDIT(0,91,1024,60,IDC_EDIT_PASSWORD,"",&font22,0xffffff),
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
// WS_EX_AUTOSECONDARYDC,
WS_EX_NONE,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "Fpsd",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formPasswordProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
.auto_close_time_set = 30,
};
static struct Keyboards keys[] = {
{"0","0","["},
{"1","1","]"},
{"2","2","{"},
{"3","3","}"},
{"4","4","#"},
{"5","5","%"},
{"6","6","^"},
{"7","7","*"},
{"8","8","+"},
{"9","9","="},
{"q","Q","_"},
{"w","W","\\"},
{"e","E","|"},
{"r","R","~"},
{"t","T","<"},
{"y","Y",">"},
{"u","U","U"},
{"i","I","I"},
{"o","O","¥"},
{"p","P","·"},
{"ABC","abc","-"},
{"a","A","/"},
{"s","S",":"},
{"d","D",";"},
{"f","F","("},
{"g","G",")"},
{"h","H","$"},
{"j","J","&"},
{"k","K","@"},
{"l","L","\""},
{"#+=","#+=","abc"},
{"z","Z","abc"},
{"x","X","'"},
{"c","C","."},
{"v","V",","},
{"b","B","?"},
{"n","N","!"},
{"m","M","'"},
{"\b","\b","\b"},
{NULL},
};
static MyCtrlButton ctrls_button[] = {
{0},
};
static MyCtrlTitle ctrls_title[] = {
{
IDC_TITLE,
MYTITLE_LEFT_EXIT,
MYTITLE_RIGHT_TEXT,
0,0,1024,40,
"输入密码",
"确定",
0xffffff, 0x333333FF,
buttonNotify,
},
{0},
};
static FormBase* form_base = NULL;
static void enableAutoClose(void)
{
Screen.setCurrent(form_base_priv.name);
flag_timer_stop = 0;
}
static void updateTitle(void)
{
if (form_password_type == FOMR_TYPE_PASSWORD) {
SendMessage(GetDlgItem(form_base->hDlg,IDC_TITLE),
MSG_MYTITLE_SET_TITLE,(WPARAM)"输入密码",0);
} else if (form_password_type == FOMR_TYPE_ACCOUNT) {
SendMessage(GetDlgItem(form_base->hDlg,IDC_TITLE),
MSG_MYTITLE_SET_TITLE,(WPARAM)"输入账号",0);
}
}
/* ----------------------------------------------------------------*/
/**
* @brief buttonNotify 退出按钮
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ----------------------------------------------------------------*/
static void buttonNotify(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc == MYTITLE_BUTTON_EXIT)
ShowWindow(GetParent(hwnd),SW_HIDE);
else if (nc == MYTITLE_BUTTON_TEXT) {
char text[64] = {0};
int ret = SendMessage(GetDlgItem(GetParent(hwnd),IDC_EDIT_PASSWORD),
MSG_GETTEXT,64,(LPARAM)text);
if (ret == 0)
return;
if (form_password_type == FOMR_TYPE_ACCOUNT) {
form_password_type = <PASSWORD>_TYPE_PASSWORD;
strcpy(g_account,text);
updateTitle();
} else {
if (getPasswordProc)
getPasswordProc(g_account,text);
ShowWindow(GetParent(hwnd),SW_HIDE);
}
}
SendMessage(GetDlgItem(GetParent(hwnd),IDC_EDIT_PASSWORD),MSG_SETTEXT,0,(LPARAM)"");
}
static void keboardNotify(HWND hwnd, int click_type,int index)
{
static int largeabc_index = 0; // 记录下需要改变的图标下标
if (index < 0) {
if (keys[kb_data.index].state == BN_PUSHED
&& click_type == BN_UNPUSHED ) {
keys[kb_data.index].state = BN_UNPUSHED;
InvalidateRect (hwnd, &keys[kb_data.index].rc, FALSE);
}
return;
}
if (click_type == BN_PUSHED) {
keys[index].state = BN_PUSHED;
InvalidateRect (hwnd, &keys[index].rc, FALSE);
return;
}
RECT rc ;
keys[index].state = BN_UNPUSHED;
rc.left = 0;
rc.right = 1024;
rc.top = 190;
rc.bottom = 600;
if (strcmp(keys[index].func[kb_data.key_type],"ABC") == 0) {
kb_data.key_type = 1;
InvalidateRect (hwnd, &rc, FALSE);
} else if (strcmp(keys[index].func[kb_data.key_type],"abc") == 0) {
if (kb_data.key_type == 2)
re_paint_abc = 1;
kb_data.key_type = 0;
if (largeabc_index != 0) {
keys[largeabc_index].bmp_nor = &bmp_key_nor;
keys[largeabc_index].bmp_pre = &bmp_key_pre;
keys[largeabc_index].rc.right = keys[largeabc_index].rc.left + keys[largeabc_index].bmp_nor->bmWidth;
keys[largeabc_index].rc.bottom = keys[largeabc_index].rc.top + keys[largeabc_index].bmp_pre->bmHeight;
keys[largeabc_index+1].bmp_nor = &bmp_key_nor;
keys[largeabc_index+1].bmp_pre = &bmp_key_pre;
keys[largeabc_index+1].rc.right = keys[largeabc_index+1].rc.left + keys[largeabc_index+1].bmp_nor->bmWidth;
keys[largeabc_index+1].rc.bottom = keys[largeabc_index+1].rc.top + keys[largeabc_index+1].bmp_pre->bmHeight;
}
InvalidateRect (hwnd, &rc, FALSE);
} else if (strcmp(keys[index].func[kb_data.key_type],"#+=") == 0) {
largeabc_index = index;
kb_data.key_type = 2;
// 针对acb图标变化的情况,修改图片与刷新范围
keys[largeabc_index].bmp_nor = &bmp_key_abc_nor;
keys[largeabc_index].bmp_pre = &bmp_key_abc_pre;
keys[largeabc_index].rc.right = keys[largeabc_index].rc.left + keys[largeabc_index].bmp_nor->bmWidth;
keys[largeabc_index].rc.bottom = keys[largeabc_index].rc.top + keys[largeabc_index].bmp_pre->bmHeight;
keys[largeabc_index+1].bmp_nor = NULL;
keys[largeabc_index+1].bmp_pre = NULL;
keys[largeabc_index+1].rc.right = keys[largeabc_index+1].rc.left;
keys[largeabc_index+1].rc.bottom = keys[largeabc_index+1].rc.top;
InvalidateRect (hwnd, &rc, FALSE);
} else {
SendMessage(GetDlgItem(hwnd,IDC_EDIT_PASSWORD),MSG_CHAR,keys[index].func[kb_data.key_type][0],0);
InvalidateRect (hwnd, &keys[index].rc, FALSE);
}
}
void formPasswordLoadBmp(void)
{
if (bmp_load_finished == 1)
return;
printf("[%s]\n", __FUNCTION__);
bmpsLoad(bmp_load);
my_button->bmpsLoad(ctrls_button,BMP_LOCAL_PATH);
bmp_load_finished = 1;
}
static void initKeyboard(void)
{
int x_start = 15,y_start = 196,w = bmp_key_nor.bmWidth + 21, h = bmp_key_nor.bmHeight + 22;
int i,j = -1;
for (i=0; keys[i].func[0] != NULL; i++) {
if (i % 10 == 0) {
j++;
keys[i].rc.left = x_start;
keys[i].rc.top = y_start + h * j;
} else {
keys[i].rc.left = x_start + (i % 10) * w;
keys[i].rc.top = y_start + h * j;
}
keys[i].bmp_nor = &bmp_key_nor;
keys[i].bmp_pre = &bmp_key_pre;
keys[i].rc.right = keys[i].rc.left + keys[i].bmp_nor->bmWidth;
keys[i].rc.bottom = keys[i].rc.top + keys[i].bmp_pre->bmHeight;
keys[i].state = BN_UNPUSHED;
}
// 删除键用其他的图片
keys[i-1].bmp_nor = &bmp_key_delete_nor;
keys[i-1].bmp_pre = &bmp_key_delete_pre;
keys[i-1].rc.right = keys[i-1].rc.left + keys[i-1].bmp_nor->bmWidth;
keys[i-1].rc.bottom = keys[i-1].rc.top + keys[i-1].bmp_pre->bmHeight;
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_title[i].idc != 0; i++) {
ctrls_title[i].font = font20;
createMyTitle(hDlg,&ctrls_title[i]);
}
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
createMyButton(hDlg,&ctrls_button[i]);
}
SendMessage (GetDlgItem(hDlg,IDC_EDIT_PASSWORD), EM_LIMITTEXT, 64, 0L);
initKeyboard();
updateTitle();
}
static void paint(HWND hWnd,HDC hdc)
{
#define FILL_BMP_STRUCT(rc,img) rc.left, rc.top,img->bmWidth,img->bmHeight,img
int i;
SetPenColor (hdc, 0x12345678);
MoveTo (hdc, 0, 90);
LineTo (hdc, 1024,90);
MoveTo (hdc, 0, 151);
LineTo (hdc, 1024,151);
SetTextColor(hdc,COLOR_lightwhite);
SetBkMode(hdc,BM_TRANSPARENT);
SelectFont (hdc, font20);
if (re_paint_abc) {
re_paint_abc = 0;
SetBrushColor (hdc,0);
FillBox (hdc, 16,502,180,80);
}
for (i=0; keys[i].func[0] != NULL; i++) {
if (keys[i].state == BN_UNPUSHED) {
if (keys[i].bmp_nor)
FillBoxWithBitmap(hdc,FILL_BMP_STRUCT(keys[i].rc,keys[i].bmp_nor));
} else if (keys[i].state == BN_PUSHED) {
if (keys[i].bmp_pre)
FillBoxWithBitmap(hdc,FILL_BMP_STRUCT(keys[i].rc,keys[i].bmp_pre));
}
if (keys[i].func[kb_data.key_type])
DrawText (hdc,keys[i].func[kb_data.key_type], -1, &keys[i].rc,
DT_CENTER | DT_VCENTER | DT_WORDBREAK | DT_SINGLELINE);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief clickInButton 判断触摸坐标是否在按钮内
*
* @param pInfo
* @param x
* @param y
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int clickInButton(int x,int y)
{
RECT *rc ;
int i;
for (i=0; keys[i].func[0] != NULL; i++) {
rc = &keys[i].rc;
if (PtInRect (rc, x, y) && PtInRect (rc, kb_data.click_x,kb_data.click_y))
return i;
}
return -1;
}
/* ----------------------------------------------------------------*/
/**
* @brief formPasswordProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ----------------------------------------------------------------*/
static int formPasswordProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
switch(message) // 自定义消息
{
case MSG_TIMER:
{
if (flag_timer_stop)
return 0;
} break;
case MSG_LBUTTONDOWN:
{
int x, y;
x = LOSWORD(lParam);
y = HISWORD(lParam);
if (GetCapture () == hDlg)
break;
SetCapture (hDlg);
kb_data.click_x = x;
kb_data.click_y = y ;
kb_data.index = clickInButton(x,y);
keboardNotify(hDlg,BN_PUSHED,kb_data.index);
}
break;
case MSG_LBUTTONUP:
{
int x, y;
if (GetCapture() != hDlg) {
// if(pInfo->state!=BUT_NORMAL) {
// pInfo->state = BUT_NORMAL;
// InvalidateRect (hwnd, NULL, TRUE);
// }
break;
}
ReleaseCapture ();
x = LOSWORD(lParam);
y = HISWORD(lParam);
int index = clickInButton(x,y);
keboardNotify(hDlg,BN_UNPUSHED,index);
} break;
case MSG_PAINT:
hdc = BeginPaint (hDlg);
paint(hDlg,hdc);
EndPaint (hDlg, hdc);
return 0;
case MSG_ENABLE_WINDOW:
enableAutoClose();
break;
case MSG_DISABLE_WINDOW:
flag_timer_stop = 1;
break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormPassword(HWND hMainWnd,char *account,
void (*callback)(void),
void (*getPassword)(char *account,char *password))
{
HWND Form = Screen.Find(form_base_priv.name);
getPasswordProc = getPassword;
memset(g_account,0,sizeof(g_account));
if (account) {
strcpy(g_account,account);
form_password_type = FOMR_TYPE_PASSWORD;
} else
form_password_type = FOMR_TYPE_ACCOUNT;
if(Form) {
updateTitle();
ShowWindow(Form,SW_SHOWNORMAL);
Screen.setCurrent(form_base_priv.name);
} else {
if (bmp_load_finished == 0) {
// topMessage(hMainWnd,TOPBOX_ICON_LOADING,NULL );
return 0;
}
form_base_priv.callBack = callback;
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
<file_sep>/src/gui/my_controls/my_dialog.c
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include "commongdi.h"
#include "cliprect.h"
#include "internals.h"
#include "ctrlclass.h"
#include "my_dialog.h"
HWND GUIAPI CreateMyWindowIndirectParamEx (PMY_DLGTEMPLATE pDlgTemplate,
HWND hOwner, WNDPROC WndProc, LPARAM lParam,
const char* werdr_name, WINDOW_ELEMENT_ATTR* we_attrs,
const char* window_name, const char* layer_name)
{
MAINWINCREATE CreateInfo;
HWND hMainWin;
int i;
PMY_CTRLDATA pCtrlData;
HWND hCtrl;
HWND hFocus;
if (pDlgTemplate->controlnr > 0 && !pDlgTemplate->controls)
return HWND_INVALID;
hOwner = GetMainWindowHandle (hOwner);
CreateInfo.dwReserved = (DWORD)pDlgTemplate;
CreateInfo.dwStyle = pDlgTemplate->dwStyle & ~WS_VISIBLE;
CreateInfo.dwExStyle = pDlgTemplate->dwExStyle ;//| WS_EX_AUTOSECONDARYDC;
CreateInfo.spCaption = pDlgTemplate->caption;
CreateInfo.hMenu = pDlgTemplate->hMenu;
CreateInfo.hCursor = GetSystemCursor (IDC_ARROW);
CreateInfo.hIcon = pDlgTemplate->hIcon;
CreateInfo.MainWindowProc = WndProc ? WndProc : DefaultMainWinProc;
CreateInfo.lx = pDlgTemplate->x;
CreateInfo.ty = pDlgTemplate->y;
CreateInfo.rx = pDlgTemplate->x + pDlgTemplate->w;
CreateInfo.by = pDlgTemplate->y + pDlgTemplate->h;
CreateInfo.iBkColor =
0;
CreateInfo.dwAddData = pDlgTemplate->dwAddData;
CreateInfo.hHosting = hOwner;
hMainWin = CreateMainWindowEx (&CreateInfo,
werdr_name, we_attrs, window_name, layer_name);
if (hMainWin == HWND_INVALID)
return HWND_INVALID;
for (i = 0; i < pDlgTemplate->controlnr; i++) {
pCtrlData = pDlgTemplate->controls + i;
hCtrl = CreateWindowEx2 (pCtrlData->class_name,
pCtrlData->caption,
pCtrlData->dwStyle | WS_CHILD,
pCtrlData->dwExStyle,
pCtrlData->id,
pCtrlData->x,
pCtrlData->y,
pCtrlData->w,
pCtrlData->h,
hMainWin,
pCtrlData->werdr_name,
pCtrlData->we_attrs,
pCtrlData->dwAddData);
if (hCtrl == HWND_INVALID) {
DestroyMainWindow (hMainWin);
MainWindowThreadCleanup (hMainWin);
return HWND_INVALID;
}
if (pCtrlData->font != NULL)
SetWindowFont(hCtrl,*pCtrlData->font);
SetWindowElementAttr(hCtrl, WE_FGC_WINDOW, pCtrlData->font_color);
}
#if 0
hFocus = GetNextDlgTabItem (hMainWin, (HWND)0, FALSE);
#else
/* houhh 20100706, set the forefront control as focus. */
{
PCONTROL pCtrl;
for (pCtrl = (PCONTROL)(((PMAINWIN)hMainWin)->hFirstChild);
pCtrl && pCtrl->next; pCtrl = pCtrl->next);
hFocus = (HWND)pCtrl;
}
#endif
if (SendMessage (hMainWin, MSG_INITDIALOG, hFocus, lParam)) {
if (hFocus)
SetFocus (hFocus);
}
if (!(pDlgTemplate->dwExStyle & WS_EX_DLGHIDE)) {
ShowWindow (hMainWin, SW_SHOWNORMAL);
}
return hMainWin;
}
<file_sep>/src/app/udp_talk/udp_talk_parse.c
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "udp_talk_parse.h"
#include "udp_client.h"
extern unsigned int PacketID;
#define MAXMTU (1400) //xb modify 20150821
unsigned int GetIPBySockAddr(const void *Data)
{
struct sockaddr_in * addr = (struct sockaddr_in*)Data;
return addr->sin_addr.s_addr;
}
int my_inet_addr(const char *IP)
{
return inet_addr(IP);
}
//----------------------------------------------------------------------------
static void TRTPObject_SetPeerPort(TRTPObject *This,int PeerPort)
{
This->PeerPort = PeerPort;
//printf("Set 2 PeerPort=%d\n", PeerPort);
}
//---------------------------------------------------------------------------
static void TRTPObject_Destroy(TRTPObject *This)
{
This->udp->Destroy(This->udp);
free(This);
This = NULL;
}
void DelayMs(int ms);
#define PACKETHEAD ((int)(sizeof(rec_body)-MAXENCODEPACKET))
//分包发送方式,将数据分为MAXMTU+PACKETHEAD长度的包进行发送
static int TRTPObject_SendBuffer(TRTPObject *This,void *pBuf,int size)
{
int i,Cnt,Pos,Len;
int PeerPort = This->PeerPort;
char *pData = (char*)pBuf;
Cnt = (size - PACKETHEAD + MAXMTU - 1) / MAXMTU;
if(Cnt==0) {
Cnt = 1;
}
rec_body *pbody = (rec_body*)pBuf;
pbody->packet_cnt = Cnt;
pbody->packet_size = MAXMTU;
pbody->dead = 0; //不通过服务器转发
Pos = PACKETHEAD;
for(i=0;i<Cnt;i++) {
pbody->packet_idx = i;
if(i) {
memcpy(&pData[Pos-PACKETHEAD],pData,PACKETHEAD);
}
//发送数据长度
Len = ((size-Pos)>MAXMTU?MAXMTU:(size-Pos))+PACKETHEAD;
This->udp->SendBuffer(This->udp,This->cPeerIP,PeerPort,
&pData[Pos-PACKETHEAD],Len);
Pos+=MAXMTU;
}
return size;
}
//---------------------------------------------------------------------------
//分包接收方式,在本函数中处理接收所有分包及拼包的过程
//---------------------------------------------------------------------------
static int TRTPObject_RecvBuffer(TRTPObject *This,void *pBuf,int size,int TimeOut)
{
unsigned int i,j,Cnt,Len;
int Pos;
unsigned int PackID;
char cTmpBuf[MAXMTU+PACKETHEAD],*pData;
rec_body *pbody = (rec_body*)pBuf;
char sockaddr[64];
unsigned int RecvIP;
int Size = sizeof(sockaddr);
pData = (char*)pBuf;
int PackSize = 0;
#if 0
unsigned int count = 0;
Pos = This->udp->RecvBuffer(This->udp,pBuf,size,TimeOut,sockaddr,&Size);
if (pbody->slen)
printf("[00]p_cnt:%02d,p_size:%d,p_idx:%02d,alen:%04d,atype:%d,tlen:%06d,dead:%d,seq:%04d,slen:%06d,vtype:%d,start\n",
pbody->packet_cnt,pbody->packet_size,pbody->packet_idx,
pbody->alen,pbody->atype,pbody->tlen,pbody->dead,pbody->seq,pbody->slen,pbody->vtype );
if (pbody->packet_idx == 0) {
count = pbody->packet_cnt;
}
for (i=1; i<count; i++) {
Pos = This->udp->RecvBuffer(This->udp,pBuf,size,TimeOut,sockaddr,&Size);
if (pbody->slen) {
if (i == count - 1) {
printf("[%02d]p_cnt:%02d,p_size:%d,p_idx:%02d,alen:%04d,atype:%d,tlen:%06d,dead:%d,seq:%04d,slen:%06d,vtype:%d,end\n",
i,pbody->packet_cnt,pbody->packet_size,pbody->packet_idx,
pbody->alen,pbody->atype,pbody->tlen,pbody->dead,pbody->seq,pbody->slen,pbody->vtype );
} else {
printf("[%02d]p_cnt:%02d,p_size:%d,p_idx:%02d,alen:%04d,atype:%d,tlen:%06d,dead:%d,seq:%04d,slen:%06d,vtype:%d |\n",
i,pbody->packet_cnt,pbody->packet_size,pbody->packet_idx,
pbody->alen,pbody->atype,pbody->tlen,pbody->dead,pbody->seq,pbody->slen,pbody->vtype );
}
if (i != pbody->packet_idx)
printf("--------------------\n");
if (Pos < 0) {
printf("err :%s\n", strerror(errno));
}
} else if (pbody->alen){
i--;
}
}
return 0;
#endif
//如果IP不对,丢弃该包
for(i=0; i<10; i++) {
Pos = This->udp->RecvBuffer(This->udp,pBuf,size,TimeOut,sockaddr,&Size);
// printf("[start %d]p_cnt:%02d,p_size:%d,p_idx:%02d,alen:%04d,atype:%d,tlen:%06d,dead:%d,seq:%04d,slen:%06d,vtype:%d\n",
// i,pbody->packet_cnt,pbody->packet_size,pbody->packet_idx,
// pbody->alen,pbody->atype,pbody->tlen,pbody->dead,pbody->seq,pbody->slen,pbody->vtype );
if(Pos <= 0) {
//接收错误,由下面过程处理
break;
}
RecvIP = GetIPBySockAddr(sockaddr);
if(RecvIP == This->dwPeerIP)
break;
}
if(i == 10) {
printf("[%s]%d\n", __FUNCTION__,__LINE__);
return 0;
}
//接收错误处理
if(Pos<PACKETHEAD) {
if(Pos<=0) {
This->RecvTimeOut++;
printf("[1]Rtp recv data timeout %d\n",This->RecvTimeOut);
if(This->RecvTimeOut<10)
return 0;
return -1;
} else {
return 0;
}
}
This->RecvTimeOut=0;
//首包索引必须为0
if(pbody->packet_idx!=0) {
return 0;
}
//保存有多少个数据包
Cnt = pbody->packet_cnt;
PackID = pbody->seq;
PackSize = pbody->packet_size;
if(Cnt==1) {
return Pos;
}
//接收剩余的分包
pbody = (rec_body*)cTmpBuf;
for(i=1;i<Cnt;i++) {
//如果IP不对,丢弃该包
for(j=0;j<10;j++) {
Len = This->udp->RecvBuffer(This->udp,cTmpBuf,MAXMTU+PACKETHEAD,TimeOut,sockaddr,&Size);
// printf("[continue %02d]p_cnt:%02d,p_size:%d,p_idx:%02d,alen:%04d,atype:%d,tlen:%06d,dead:%d,seq:%04d,slen:%06d,vtype:%d\n",
// i,pbody->packet_cnt,pbody->packet_size,pbody->packet_idx,
// pbody->alen,pbody->atype,pbody->tlen,pbody->dead,pbody->seq,pbody->slen,pbody->vtype );
if(Len<=0) {
break;
}
unsigned int RecvIP2 = GetIPBySockAddr(sockaddr);
if(RecvIP2 == RecvIP) {
break;
}
}
if(j==10)
Len = 0;
if(Len<=0) {
This->RecvTimeOut++;
printf("[2]Rtp recv data timeout %d\n",This->RecvTimeOut);
if(This->RecvTimeOut<10)
return 0;
return -1;
}
if(pbody->seq!=PackID) { //帧号错误
printf("[%s]%d,pbody->seq:%d,pckid:%d\n",
__FUNCTION__,__LINE__,
pbody->seq,PackID );
return 0;
}
if(pbody->packet_idx>=Cnt) { //分包索引错误
printf("[%s]%d\n", __FUNCTION__,__LINE__);
return 0;
}
// 中途接收分包遗漏,则接收完剩余分包后退出,丢弃该帧
if ((pbody->packet_idx+1 == pbody->packet_cnt)
&& (i != pbody->packet_idx)) {
return 0;
}
if(Len>PACKETHEAD)
memcpy(&pData[PACKETHEAD+pbody->packet_idx*MAXMTU],&cTmpBuf[PACKETHEAD],Len-PACKETHEAD);
Pos+=Len-PACKETHEAD;
}
return Pos;
}
//---------------------------------------------------------------------------
// 创建一个UDP客户端,Port为0则不绑定端口
//---------------------------------------------------------------------------
TRTPObject* TRTPObject_Create(
const char *PeerIP,
int PeerPort)
{
TRTPObject* This;
This = (TRTPObject *)malloc(sizeof(TRTPObject));
if(This==NULL) {
return NULL;
}
memset(This,0,sizeof(TRTPObject));
strcpy(This->cPeerIP,PeerIP);
This->udp = TUDPClient_Create(8800);
if(This->udp == NULL) {
free(This);
return NULL;
}
This->dwPeerIP = my_inet_addr(PeerIP);
This->DelayTime = 10;
This->PeerPort = PeerPort;
This->Destroy = TRTPObject_Destroy;
This->RecvBuffer = TRTPObject_RecvBuffer;
This->SendBuffer = TRTPObject_SendBuffer;
This->SetPeerPort = TRTPObject_SetPeerPort;
return This;
}
<file_sep>/module/singlechip/main.c
/*
* =============================================================================
*
* Filename: singlechip.c
*
* Description: 单片机通信协议
*
* Version: 1.0
* Created: 2019-06-10 13:11:39
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include "uart.h"
#include "protocol.h"
#include "config.h"
#include "my_audio.h"
#include "debug.h"
// #include "externfunc.h"
#include "ipc_server.h"
#include "thread_helper.h"
#include "queue.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
extern int playVoice(char * file_name);
extern char * excuteCmd(char *Cmd,...);
extern void sconfigLoad(void);
extern int getCapType(void);
extern int getCapCount(void);
extern int getCapTimer(void);
extern char * getCapImei(void);
extern int getBrightness(void);
extern int sIsNeedToPlay(void);
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define PACK_HEAD 0x5A
#define PACK_TAIL 0x5B
enum {
CHECK_POWER = (1 << 0),
CHECK_KEY_HOM = (1 << 1),
CHECK_KEY_DOORBELL = (1 << 2),
CHECK_KEY_PIR = (1 << 3),
CHECK_KEY_WIFI = (1 << 4),
};
// 协议内容 [5A] [leng] [id] [cmd] data[N] [checkout] [5B]
enum{
CMD_GET_VERSION = 0X00, // ARM→单片机 0X00 NBYTE 查询版本号
CMD_HEART = 0X01, // ARM→单片机 0X01 NBYTE 关机或休眠时,发送心跳到单片机
CMD_POWER = 0X02, // ARM→单片机 0X02 1BYTE 0 关机 1进入低功耗模式 2 复位WIFI
CMD_WIFI_PWD = 0X03, // ARM→单片机 0X03 32BYTE 设置WIFI连接,数据格式: SSID:[0~15]BYTE; PASSWORD:[<PASSWORD>;
CMD_WIFI_RESPONSE = 0X04, // 单片机→ARM 0X04 1BYTE WIFI连接响应,参数说明: 0X00 WIFI连接成功; 0X01 WIFI连接失败;
CMD_SERVER = 0X05, // ARM→单片机 0X05 NBYTE 设置连接服务器信息: 服务器IP:[0~3]BYTE; 设备信息:[4~N]BYTE;
CMD_SERVER_RESPONSE = 0X06, // 单片机→ARM 0X06 1BYTE 服务器连接响应: 0X00 服务器连接成功; 0X01 服务器连接失败;
CMD_SET_PIR = 0X07, // ARM→单片机 0X07 1BYTE 设置PIR距离: 0X00:近; 0X01:中; 0X02:远;
CMD_SET_PIR_RESPONSE = 0X08, // 单片机→ARM 0X08 1BYTE 设置PIR响应: 0X00 PIR设置成功; 0X01 PIR设置失败;
CMD_GET_CHECK = 0X41, // ARM→单片机 0X41 0BYTE 查询触发源;
CMD_GET_CHECK_RESPONSE = 0X42, // 单片机→ARM 0X42 3BYTE 触发源BYTE0:
/*
BIT0 开机按键触发1, 否则0;下同
BIT1 室内机按键触发;
BIT2 室外机按键触发;
BIT3 PIR信号触发;
BIT4 AP6212 WIFI信号触发;
BIT5 ESP WIFI信号触发;
BIT6 GSM 中断信号触发;
BIT7 USB 信号触发;
保留字节[1~2]BYTE,恒为0X00;
*/
CMD_REPORT_RESPONSE = 0XC8, // 单片机→ARM 0XC8 3BYTE 触发源BYTE0:
/*
BIT0 开机按键触发1, 否则0;下同
BIT1 室内机按键触发;
BIT2 室外机按键触发;
BIT3 PIR信号触发;
BIT4 AP6212 WIFI信号触发;
BIT5 ESP WIFI信号触发;
BIT6 GSM 中断信号触发;
BIT7 USB 信号触发;
保留字节[1~2]BYTE,恒为0X00;
*/
CMD_REPORT = 0XC9, // ARM→单片机 0XC9 0BYTE ARM设备发出
CMD_POWEROFF = 0XCA, // 单片机→ARM 0XCA 1BYTE 单片机长按通知关机
CMD_ERR_RESPONSE = 0xFF, // 单片机→ARM 0XFF 1BYTE 0X00 数据接收成功; 0X01 数据校验失败; 0X02 参数错误;
};
typedef struct _ProtocolComm{
uint8_t head;
uint8_t leng;
uint8_t id;
uint8_t cmd;
uint8_t data;
uint8_t checksum;
uint8_t tail;
}ProtocolComm;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static IpcServer* ipc_uart = NULL;
static Queue *video_queue = NULL;
static Queue *main_queue = NULL;
static int timer_interval = 0; // 按键时间间隔
static int cap_statue = 0; // 是否正在抓拍
static uint8_t id = 0;
static int screensaverSet(int state)
{
#define MIN_BRIGHTNESS 244
#define MAX_BRIGHTNESS 0
#ifndef X86
static int state_old = 0;
if (state == state_old)
return 0;
state_old = state;
int brightness = getBrightness();
char buf[4] = {0};
// 当设置为100时,亮度设置为0,此时灭屏,最大设置99
if (brightness == 100)
brightness--;
int real_brightness = (100 - brightness)*(MIN_BRIGHTNESS - MAX_BRIGHTNESS) / 100;
sprintf(buf,"%d",real_brightness);
if (state) {
excuteCmd("echo",buf,">","/sys/class/backlight/rk28_bl/brightness ",NULL);
} else {
excuteCmd("echo","0",">","/sys/class/backlight/rk28_bl/brightness ",NULL);
}
#endif
return 1;
}
static void getFileName(char *file_name,char *date)
{
if (!file_name || !date)
return;
time_t timer;
struct tm *tm1;
timer = time(&timer);
tm1 = localtime(&timer);
sprintf(file_name,
"%02d%02d%02d%02d%02d%02d",
(tm1->tm_year+1900) % 100,
tm1->tm_mon+1,
tm1->tm_mday,
tm1->tm_hour,
tm1->tm_min,
tm1->tm_sec);
sprintf(date,
"%04d-%02d-%02d %02d:%02d:%02d",
tm1->tm_year+1900,
tm1->tm_mon+1,
tm1->tm_mday,
tm1->tm_hour,
tm1->tm_min,
tm1->tm_sec);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cmdPacket 封装发送给单片机的指令
* 5A leng id cmd data[N] checkout 5B
*
* @param cmd
* @param id
* @param data
* @param data_len
*/
/* ---------------------------------------------------------------------------*/
static void cmdPacket(uint8_t cmd,uint8_t id,uint8_t *data,int data_len)
{
uint8_t *send_buff = NULL;
int i;
int leng = data_len + 6;
send_buff = (uint8_t *)calloc(leng,sizeof(uint8_t));
send_buff[0] = PACK_HEAD;
send_buff[1] = leng;
send_buff[2] = id;
send_buff[3] = cmd;
for (i=0; i<data_len; i++) {
send_buff[4 + i] = data[i];
}
for (i=1; i<leng-2; i++) {
send_buff[leng - 2] += send_buff[i];
}
send_buff[leng - 1] = PACK_TAIL;
if (uart)
uart->send(uart,send_buff,leng);
free(send_buff);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cmdReportResponse 回复单片机发送的消息
*/
/* ---------------------------------------------------------------------------*/
static void cmdReportResponse(void)
{
cmdPacket(CMD_REPORT,0,NULL,0);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cmdCheckStatus 查询单片机之前的状态
*/
/* ---------------------------------------------------------------------------*/
static void cmdCheckStatus(void)
{
cmdPacket(CMD_GET_CHECK,id++,NULL,0);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cmdSendHeart 关机或休眠前,不断发送心跳包,告诉单片机是否已经关机成功
*/
/* ---------------------------------------------------------------------------*/
static void cmdSendHeart(void)
{
uint8_t data = 1;
cmdPacket(CMD_HEART,id++,&data,0);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cmdPowerOff 关机
*/
/* ---------------------------------------------------------------------------*/
static void cmdPowerOff(void)
{
uint8_t data = 0;
cmdPacket(CMD_POWER,id++,&data,1);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cmdSleep 休眠
*/
/* ---------------------------------------------------------------------------*/
static void cmdSleep(void)
{
uint8_t data = 1;
cmdPacket(CMD_POWER,id++,&data,1);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cmdWifiReset 复位wifi
*/
/* ---------------------------------------------------------------------------*/
static void cmdWifiReset(void)
{
uint8_t data = 2;
cmdPacket(CMD_POWER,id++,&data,1);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cmdGetVesion 获取单片机版本号
*/
/* ---------------------------------------------------------------------------*/
static void cmdGetVesion(void)
{
cmdPacket(CMD_GET_VERSION,id++,NULL,0);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief cmdPirStrength 设置PIR强度
*
* @param strength
*/
/* ---------------------------------------------------------------------------*/
static void cmdPirStrength(int strength)
{
uint8_t data = strength;
cmdPacket(CMD_SET_PIR,id++,&data,1);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief threadCmdHeart 休眠或者关机线程不断发送心跳
*
* @param arg
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static void* threadCmdHeart(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
while (1) {
cmdSendHeart();
sleep(1);
}
return NULL;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief uartDeal 单片机协议处理
*/
/* ---------------------------------------------------------------------------*/
static void uartDeal(void)
{
uint8_t buff[512]={0};
uint8_t checksum = 0;
int index;
int i;
int leng = 0;
int len = uart->recvBuffer(uart,buff,sizeof(buff));
if (len <= 0) {
return;
}
DEBUG_UART("reci",buff,len);
for(index=0; index<len; index++){
if(buff[index] == PACK_HEAD){
leng = buff[index + 1];
if (index + leng > 512)
return;
if(buff[index + leng - 1] == PACK_TAIL){
break;
}
}
}
for (i=index+1; i<leng - 2; i++) {
checksum += buff[i];
}
if (checksum != buff[index + leng - 2])
return;
uint8_t cmd = buff[index + 3];
uint8_t *data = &buff[index + 4];
IpcData ipc_data;
switch(cmd)
{
case CMD_SET_PIR_RESPONSE:
ipc_data.pir_strength_result = data[0];
ipc_data.cmd = IPC_UART_SET_PIR;
main_queue->post(main_queue,&ipc_data);
break;
case CMD_GET_VERSION:
ipc_data.cmd = IPC_UART_GETVERSION;
ipc_data.s_version[0] = data[0];
ipc_data.s_version[1] = data[1];
ipc_data.s_version[2] = '\0';
main_queue->post(main_queue,&ipc_data);
break;
case CMD_GET_CHECK_RESPONSE:
case CMD_REPORT_RESPONSE:
cmdReportResponse();
if (data[0] & CHECK_POWER) {
ipc_data.cmd = IPC_UART_KEY_POWER;
main_queue->post(main_queue,&ipc_data);
}
if (data[0] & CHECK_KEY_HOM) {
ipc_data.cmd = IPC_UART_KEYHOME;
main_queue->post(main_queue,&ipc_data);
}
if (data[0] & CHECK_KEY_DOORBELL) {
if (timer_interval == 0) {
timer_interval = 3;
ipc_data.need_ring = 1;
// 未启动主程序时
if (access(IPC_MAIN,0) != 0) {
IpcData ipc_data_tmp;
getFileName(ipc_data_tmp.data.file.name,ipc_data_tmp.data.file.date);
ipc_data_tmp.count = getCapCount();
sprintf(ipc_data_tmp.data.file.path,"%s_%s",getCapImei(),ipc_data_tmp.data.file.name);
ipc_data_tmp.cmd = IPC_UART_CAPTURE;
video_queue->post(video_queue,&ipc_data_tmp);
main_queue->post(main_queue,&ipc_data_tmp);
if (sIsNeedToPlay()) {
excuteCmd("busybox","killall","aplay",NULL);
playVoice("/data/dingdong.wav");
}
ipc_data.need_ring = 0;
}
ipc_data.cmd = IPC_UART_DOORBELL;
main_queue->post(main_queue,&ipc_data);
}
}
if (data[0] & CHECK_KEY_PIR) {
ipc_data.cmd = IPC_UART_PIR;
main_queue->post(main_queue,&ipc_data);
}
if (data[0] & CHECK_KEY_WIFI) {
ipc_data.cmd = IPC_UART_WIFI_WAKE;
main_queue->post(main_queue,&ipc_data);
}
break;
case CMD_POWEROFF:
{
ipc_data.cmd = IPC_UART_POWEROFF;
main_queue->post(main_queue,&ipc_data);
createThread(threadCmdHeart,NULL);
}
break;
case CMD_ERR_RESPONSE:
break;
default:
break;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief ipcCallback 主APP发送消息处理
*
* @param data
* @param size
*/
/* ---------------------------------------------------------------------------*/
static void ipcCallback(char *data,int size )
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
IpcData ipc_data;
memcpy(&ipc_data,data,sizeof(IpcData));
switch(ipc_data.cmd)
{
case IPC_UART_POWEROFF:
{
cmdPowerOff();
createThread(threadCmdHeart,NULL);
}
break;
case IPC_UART_SLEEP:
{
cmdSleep();
createThread(threadCmdHeart,NULL);
}
break;
case IPC_UART_WIFI_RESET:
{
cmdWifiReset();
} break;
case IPC_UART_GETVERSION:
{
cmdGetVesion();
} break;
case IPC_UART_SET_PIR:
{
cmdPirStrength(ipc_data.pir_strength);
}break;
default:
break;
}
}
static void* threadIpcSendVideo(void *arg)
{
Queue * queue = (Queue *)arg;
waitIpcOpen(IPC_CAMMER);
IpcData ipc_data;
while (1) {
queue->get(queue,&ipc_data);
ipc_data.dev_type = IPC_DEV_TYPE_UART;
if (ipc_uart)
ipc_uart->sendData(ipc_uart,IPC_CAMMER,&ipc_data,sizeof(IpcData));
}
return NULL;
}
static void* threadIpcSendMain(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
Queue * queue = (Queue *)arg;
waitIpcOpen(IPC_MAIN);
IpcData ipc_data;
while (1) {
queue->get(queue,&ipc_data);
ipc_data.dev_type = IPC_DEV_TYPE_UART;
// printf("post:%d\n",ipc_data.cmd );
if (ipc_uart)
ipc_uart->sendData(ipc_uart,IPC_MAIN,&ipc_data,sizeof(IpcData));
}
return NULL;
}
static void* threadTimer(void *arg)
{
while (1) {
if (timer_interval) {
timer_interval--;
}
sleep(1);
}
return NULL;
}
int main(int argc, char *argv[])
{
sconfigLoad();
video_queue = queueCreate("video_queue",QUEUE_BLOCK,sizeof(IpcData));
main_queue = queueCreate("main_queue",QUEUE_BLOCK,sizeof(IpcData));
ipc_uart = ipcCreate(IPC_UART,ipcCallback);
uartInit(uartDeal);
cmdCheckStatus();
cmdWifiReset();
screensaverSet(1);
// screensaverSet(0);
mkdir(FAST_PIC_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
createThread(threadIpcSendVideo,video_queue);
createThread(threadIpcSendMain,main_queue);
createThread(threadTimer,NULL);
debugInit();
pause();
return 0;
}
<file_sep>/include/ucpaas/ucs_defines.h
/*
* Copyright (c) 2017 The UCPAAS project authors. All Rights Reserved.
*
*/
#ifndef __UCS_INCLUDE_BASE_DEFINES_H__
#define __UCS_INCLUDE_BASE_DEFINES_H__
#ifdef __cplusplus
extern "C"{
#endif /* End of #ifdef __cplusplus */
#define UCS_MAX_USERID_STR_LEN 32
#define UCS_MAX_PHONE_STR_LEN 32
#define UCS_MAX_BRAND_STR_LEN 32
#define UCS_MAX_CALLID_STR_LEN 32
#define UCS_MAX_IP_STR_LEN 48
#define UCS_MAX_NICKNAME_STR_LEN 64
#define UCS_MAX_VERSION_STR_LEN 64
#define UCS_MAX_USERDATA_STR_LEN 128
#define UCS_MAX_APPID_STR_LEN 128
#define UCS_MAX_TCP_TRANS_DATA_LEN 512
#define UCS_MIN_USER_TOKEN_STR_LEN 100
#define UCS_MAX_USER_TOKEN_STR_LEN 256
typedef enum
{
eUCS_REASON_SUCCESS = 300000,
/* 300001 ~ 300099 is connect reason */
/* tcp connection established */
eUCS_REASON_TCP_CONNECTED = 300001,
/* tcp connection reconnected */
eUCS_REASON_TCP_RECONNECTED = 300002,
/* tcp connection disconnected */
eUCS_REASON_TCP_DISCONNECTED = 300003,
eUCS_REASON_TCP_SEND = 300004,
eUCS_REASON_TCP_RECV = 300005,
/* tcp through data is empty */
eUCS_REASON_TCP_TRANS_EMPTY = 300010,
/* tcp through data too large */
eUCS_REASON_TCP_TRANS_2_LARGE = 300011,
/* tcp through targetid not exist */
eUCS_REASON_TCP_TRANS_TARGET_UNEXIST = 300012,
/* tcp through targetid offline */
eUCS_REASON_TCP_TRANS_TARGET_OFFLINE = 300013,
/* tcp through proxy server internal error */
eUCS_REASON_TCP_TRANS_PROXY_ERROR = 300014,
/* tcp through data send timeout */
eUCS_REASON_TCP_TRANS_SEND_TIMEOUT = 300015,
/* 300100 ~ 300199 is login reason */
/* cloud platform login successed */
eUCS_REASON_LOGIN_SUCCESS = 300100,
/* login failed caused by invalid token */
eUCS_REASON_TOKEN_INVALID = <PASSWORD>,
/* login failed caused by error arguments */
eUCS_REASON_LOGIN_ARG_ERR = 300102,
/* login failed caused by proxy server error */
eUCS_REASON_LOGIN_SYS_ERR = 300103,
/* login failed caused by wrong password */
eUCS_REASON_LOGIN_PWD_ERR = <PASSWORD>,
/* login failed caused no proxys */
eUCS_REASON_INVALID_PROXYS_NUM = 300105,
/* 300200 ~ 300299 is call reason */
eUCS_REASON_RINGING = 300200,
eUCS_REASON_CONNECTING = 300201,
/* dial failed caused by wrong called */
eUCS_REASON_INVALID_CALLED = 300202,
/* dial failed caused by called offline */
eUCS_REASON_CALLED_OFFLINE = 300203,
/* dial failed caused by called in busy */
eUCS_REASON_CALLED_BUSY = 300204,
/* dial failed caused by called reject the call */
eUCS_REASON_CALLED_REJECT = 300205,
/* dial failed caused by called not answer */
eUCS_REASON_CALLED_NO_ANSWER = 300206,
/* dial failed caused by called has frozen */
eUCS_REASON_CALLED_FROZEN = 300207,
/* dial failed caused by caller has frozen */
eUCS_REASON_CALLER_FROZEN = 300208,
/* dial failed caused by caller has expired */
eUCS_REASON_CALLER_EXPIRED = 300209,
/* dial failed caused by caller insufficient balance */
eUCS_REASON_NO_BALANCE = 300210,
/* dial failed caused by signal message timeout */
eUCS_REASON_MSG_TIMEOUT = 300211,
/* dial failed caused by caller in black list */
eUCS_REASON_BLACKlIST = 300212,
/* hangup by remote peer */
eUCS_REASON_HANGUP_BYPEER = 300213,
/* hangup by local */
eUCS_REASON_HANGUP_MYSELF = 300214,
/* call failed caused by media consultation failed */
eUCS_REASON_MEDIA_NOT_ACCEPT = 300215,
/* call hangup caused by relay server rtp received timeout */
eUCS_REASON_RTPP_TIMEOUT = 300216,
/* call hangup caused by media update failed */
eUCS_REASON_MEDIA_UPDATE_FAILED = 300217,
/* dial cancel by caller */
eUCS_REASON_CALLER_CANCEL = 300218,
/* dial failed caused by forbidden dialing */
eUCS_REASON_FORBIDDEN = 300219,
/* call hangup caused by local rtp packets received timeout */
eUCS_REASON_RTP_RECEIVED_TIMEOUT = 300220,
/* hangup failed caused by not exist call */
eUCS_REASON_CALLID_NOT_EXIST = 300221,
/* dial failed caused by caller not login successed */
eUCS_REASON_NOT_LOGGED_IN = 300222,
/* dial failed caused by server internal error */
eUCS_REASON_INTERNAL_SRV_ERROR = 300223,
eUCS_REASON_UNDEFINE = 399999
} eUcsReason;
typedef enum
{
eUCS_CALL_TYPE_AUDIO_FREE_CALL = 0x01,
eUCS_CALL_TYPE_AUDIO_DIRECT_CALL = 0x02,
eUCS_CALL_TYPE_VIDEO_CALL = 0x03
} eUcsCallType;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif // __UCS_INCLUDE_BASE_DEFINES_H__
<file_sep>/src/gui/my_controls/my_static.c
/*
* =====================================================================================
*
* Filename: MyStatic.c
*
* Description: 自定义按钮
*
* Version: 1.0
* Created: 2015-12-09 16:22:37
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
/* ----------------------------------------------------------------*
* include head files
*-----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include "my_static.h"
#include "debug.h"
#include "cliprect.h"
#include "internals.h"
#include "ctrlclass.h"
/* ----------------------------------------------------------------*
* extern variables declare
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*
* internal functions declare
*-----------------------------------------------------------------*/
static int myStaticControlProc (HWND hwnd, int message, WPARAM wParam, LPARAM lParam);
/* ----------------------------------------------------------------*
* macro define
*-----------------------------------------------------------------*/
#define CTRL_NAME CTRL_MYSTATIC
/* ----------------------------------------------------------------*
* variables define
*-----------------------------------------------------------------*/
MyControls *my_static;
/* ---------------------------------------------------------------------------*/
/**
* @brief myStaticRegist 注册控件
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static BOOL myStaticRegist (void)
{
WNDCLASS WndClass;
WndClass.spClassName = CTRL_NAME;
WndClass.dwStyle = WS_NONE;
WndClass.dwExStyle = WS_EX_NONE;
WndClass.hCursor = GetSystemCursor (IDC_ARROW);
WndClass.iBkColor = 0;
WndClass.WinProc = myStaticControlProc;
return RegisterWindowClass(&WndClass);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myStaticCleanUp 卸载控件
*/
/* ---------------------------------------------------------------------------*/
static void myStaticCleanUp (void)
{
UnregisterWindowClass(CTRL_NAME);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief paint 主要绘图函数
*
* @param hWnd
* @param hdc
*/
/* ---------------------------------------------------------------------------*/
static void paint(HWND hWnd,HDC hdc)
{
#define FILL_BMP_STRUCT(rc,img) rc.left, rc.top,img->bmWidth,img->bmHeight,img
RECT rc_bmp,rc_text;
PCONTROL pCtrl;
pCtrl = Control (hWnd);
GetClientRect (hWnd, &rc_bmp);
rc_text = rc_bmp;
if (!pCtrl->dwAddData2)
return;
MyStaticCtrlInfo* pInfo = (MyStaticCtrlInfo*)(pCtrl->dwAddData2);
if (pInfo->flag == MYSTATIC_TYPE_TEXT_AND_IMG)
FillBoxWithBitmap(hdc,FILL_BMP_STRUCT(rc_bmp,pInfo->image));
else if (pInfo->flag == MYSTATIC_TYPE_TEXT
|| pInfo->flag == MYSTATIC_TYPE_IMG_ONLY)
myFillBox(hdc,&rc_bmp,pInfo->bkg_color);
if (pInfo->flag == MYSTATIC_TYPE_IMG_ONLY)
return;
SetTextColor(hdc,pInfo->font_color);
SetBkMode(hdc,BM_TRANSPARENT);
SelectFont (hdc, pInfo->font);
DrawText (hdc,pInfo->text, -1, &rc_text,
DT_CENTER | DT_VCENTER | DT_WORDBREAK | DT_SINGLELINE);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myStaticControlProc 控件主回调函数
*
* @param hwnd
* @param message
* @param wParam
* @param lParam
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int myStaticControlProc (HWND hwnd, int message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PCONTROL pCtrl;
DWORD dwStyle;
MyStaticCtrlInfo* pInfo;
pCtrl = Control (hwnd);
pInfo = (MyStaticCtrlInfo*)pCtrl->dwAddData2;
dwStyle = GetWindowStyle (hwnd);
switch (message) {
case MSG_CREATE:
{
MyStaticCtrlInfo* data = (MyStaticCtrlInfo*)pCtrl->dwAddData;
pInfo = (MyStaticCtrlInfo*) calloc (1, sizeof (MyStaticCtrlInfo));
if (pInfo == NULL)
return -1;
memset(pInfo,0,sizeof(MyStaticCtrlInfo));
pInfo->image= data->image;
pInfo->flag = data->flag;
strcpy(pInfo->text,data->text);
pInfo->font = data->font;
pInfo->bkg_color= data->bkg_color;
pInfo->font_color= data->font_color;
pCtrl->dwAddData2 = (DWORD)pInfo;
return 0;
}
case MSG_DESTROY:
free(pInfo);
break;
case MSG_PAINT:
hdc = BeginPaint (hwnd);
paint(hwnd,hdc);
EndPaint (hwnd, hdc);
return 0;
case MSG_MYSTATIC_SET_TITLE:
if (wParam)
strcpy(pInfo->text,(char*)wParam);
InvalidateRect (hwnd, NULL, TRUE);
break;
default:
break;
}
return DefaultControlProc (hwnd, message, wParam, lParam);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief bmpsMainStaticLoad 加载主界面图片
*
* @param controls
**/
/* ---------------------------------------------------------------------------*/
static void myStaticBmpsLoad(void *ctrls,char *path)
{
int i;
char image_path[128] = {0};
MyCtrlStatic *controls = (MyCtrlStatic *)ctrls;
for (i=0; controls->idc != 0; i++) {
if (controls->flag == MYSTATIC_TYPE_TEXT_AND_IMG) {
sprintf(image_path,"%s%s.png",path,controls->img_name);
bmpLoad(&controls->image, image_path);
}
controls++;
}
}
static void myStaticBmpsRelease(void *ctrls)
{
int i;
MyCtrlStatic *controls = (MyCtrlStatic *)ctrls;
for (i=0; controls->idc != 0; i++) {
bmpRelease(&controls->image);
controls++;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief createMyStatic 创建单个静态控件
*
* @param hWnd
* @param id
* @param x,y,w,h 坐标
* @param image_normal 正常图片
* @param image_press 按下图片
* @param display 是否显示 0不显示 1显示
* @param mode 是否为选择模式 0非选择 1选择
* @param notif_proc 回调函数
*/
/* ---------------------------------------------------------------------------*/
HWND createMyStatic(HWND hWnd,MyCtrlStatic *ctrl)
{
HWND hCtrl;
MyStaticCtrlInfo pInfo;
pInfo.image= &ctrl->image;
pInfo.flag = ctrl->flag;
if (ctrl->text)
strcpy(pInfo.text,ctrl->text);
pInfo.font = ctrl->font;
pInfo.bkg_color= ctrl->bkg_color;
pInfo.font_color= ctrl->font_color;
hCtrl = CreateWindowEx(CTRL_NAME,"",WS_VISIBLE|WS_CHILD,WS_EX_TRANSPARENT,
ctrl->idc,ctrl->x,ctrl->y,ctrl->w,ctrl->h, hWnd,(DWORD)&pInfo);
return hCtrl;
}
void initMyStatic(void)
{
my_static = (MyControls *)malloc(sizeof(MyControls));
my_static->regist = myStaticRegist;
my_static->unregist = myStaticCleanUp;
my_static->bmpsLoad = myStaticBmpsLoad;
my_static->bmpsRelease = myStaticBmpsRelease;
}
<file_sep>/module/cap/process/md_display_process.h
#ifndef __DISPLAY_PROCESS_H_
#define __DISPLAY_PROCESS_H_
#include <CameraHal/StrmPUBase.h>
#include <rk_fb/rk_fb.h>
#include <rk_rga/rk_rga.h>
class DisplayProcess : public StreamPUBase {
public:
DisplayProcess();
virtual ~DisplayProcess();
bool processFrame(std::shared_ptr<BufferBase> input,
std::shared_ptr<BufferBase> output) override;
void capture(char *file_name);
int getWidth(void) const {
return width_;
}
int getHeight(void) const {
return height_;
}
private:
int rga_fd;
int width_;
int height_;
};
#endif // __DISPLAY_PROCESS_H_
<file_sep>/module/updater/partition/partition.cpp
#include "partition.h"
#include "crc32.h"
#ifdef USE_EMMC
//build/setting-emmc-sec-rootfs-abpart.ini
static struct_setting_ini g_setting_ini[8] = {
{"Fw Header", "", "/dev/mmcblk0", "", 0},
{"UserPart1", "IDBlock", "/dev/mmcblk0p2", "", PART_IDBLOCK},
{"UserPart2", "kernel", "/dev/mmcblk0p3", "", PART_KERNEL},
{"UserPart3", "dtb", "/dev/mmcblk0p4", "", PART_DTB},
{"UserPart4", "userdata", "/dev/mmcblk0p5", "data", PART_USER},
{"UserPart5", "root", "/dev/mmcblk0p6", "root", PART_BOOT},
{"UserPart6", "kernel_b", "/dev/mmcblk0p7", "", PART_KERNEL},
{"UserPart7", "dtb_b", "/dev/mmcblk0p8", "", PART_DTB},
};
#endif
#ifdef USE_NOR
//build/setting-sec-rootfs.ini
static struct_setting_ini g_setting_ini[8] = {
{"Fw Header", "", "/dev/mtdblock8", "", 0},
{"UserPart1", "IDBlock", "/dev/mtdblock1", "", PART_IDBLOCK},
{"UserPart2", "dsp", "/dev/mtdblock2", "", PART_USER},
{"UserPart3", "kernel", "/dev/mtdblock3", "", PART_KERNEL},
{"UserPart4", "dtb", "/dev/mtdblock4", "", PART_DTB},
{"UserPart5", "userdata", "/dev/mtdblock5", "data", PART_USER},
{"UserPart6", "root", "/dev/mtdblock6", "root", PART_BOOT},
{"UserPart7", "face_model", "/dev/mtdblock7", "root/usr/face_model",PART_USER},
};
#endif
#define BUFFER_64K (1024<<6)
unsigned int RKPartition::getFileSize(char* filename)
{
FILE *fp = fopen(filename, "r");
if (!fp)
return -1;
fseek(fp, 0L, SEEK_END);
unsigned int size = ftell(fp);
fclose(fp);
return size;
}
int RKPartition::readFile(int fd, void *buffer, int size)
{
int readcnd = 0;
int ret = 0;
unsigned char *p = (unsigned char*)buffer;
if (NULL == p) {
printf("%s invalid input params \n", __FUNCTION__);
return -1;
}
readcnd = 0;
ret = 0;
while (readcnd < size) {
ret = read(fd, p + readcnd, size - readcnd);
if (ret <= 0) {
if (ret < 0) {
perror("read");
}
return readcnd;
}
readcnd += ret;
}
return readcnd;
}
int RKPartition::writeFile(int fd, void *buffer, int size)
{
int writecnd = 0;
int ret = 0;
unsigned char *p = (unsigned char*)buffer;
if (NULL == p) {
printf("%s invalid input params \n", __FUNCTION__);
return -1;
}
writecnd = 0;
ret = 0;
while (writecnd < size) {
ret = write(fd, p + writecnd, size - writecnd);
if (ret <= 0) {
printf("ret = %d\n", ret);
if (ret < 0) {
perror("write");
}
return -1;
}
writecnd += ret;
}
return writecnd;
}
int RKPartition::getFwPartInfo(struct_part_info *Info)
{
int imagefd;
imagefd = open(imagepath, O_RDONLY);
if (imagefd < 0) {
printf("Firmware open %s failed \n", imagepath);
return -1;
}
if (read(imagefd, Info, sizeof(struct_part_info)) <= 0) {
printf("Firmware read %s failed \n", imagepath);
return -1;
}
if (Info->hdr.uiFwTag != RK_PARTITION_TAG) {
printf("Firmware Tag error\n");
return -1;
}
close(imagefd);
return 0;
}
int RKPartition::getStoragePartInfo(struct_part_info *Info)
{
int flashfd;
flashfd = open(g_setting_ini[0].storge_path, O_RDONLY);
if (flashfd < 0) {
printf("Flash open %s failed \n", g_setting_ini[0].storge_path);
return -1;
}
if (read(flashfd, Info, sizeof(struct_part_info)) <= 0) {
printf("Flash read %s failed \n", g_setting_ini[0].storge_path);
return -1;
}
if (Info->hdr.uiFwTag != RK_PARTITION_TAG) {
printf("Flash Tag error\n");
return -1;
}
close(flashfd);
return 0;
}
int RKPartition::setStoragePartInfo(struct_part_info *Info)
{
int flashfd;
flashfd = open(g_setting_ini[0].storge_path, O_RDWR);
if (flashfd < 0) {
printf("Flash open %s failed \n", g_setting_ini[0].storge_path);
return -1;
}
if (write(flashfd, Info, sizeof(struct_part_info)) <= 0) {
printf("Flash write %s failed \n", g_setting_ini[0].storge_path);
return -1;
}
if (Info->hdr.uiFwTag != RK_PARTITION_TAG) {
printf("Flash Tag error\n");
return -1;
}
fsync(flashfd);
sync();
sleep(1);
fsync(flashfd);
sync();
close(flashfd);
return 0;
}
int RKPartition::setPartBootPriority(struct_part_info *Info, int parttype)
{
int index[2];
if (parttype == PART_KERNEL || parttype == PART_DTB) {
index[0] = getAPartIndex_bytype(*Info, parttype);
index[1] = getBPartIndex_bytype(*Info, parttype);
Info->part[index[0]].uiPartProperty = 1;
Info->part[index[1]].uiPartProperty = 0;
printf("\told BootPriority index %d > index %d\n", index[0], index[1]);
printf("\tnew BootPriority index %d > index %d\n", index[1], index[0]);
setStoragePartInfo(Info);
}
return 0;
}
void RKPartition::debugPartsInfos(struct_part_info *info)
{
printf("PartsInfos:\n");
printf("\t :%x\n", info->hdr.uiFwTag);
for (int i = 0; i < info->hdr.uiPartEntryCount; i++) {
printf("\tszName:%s\n", info->part[i].szName);
printf("\t\t tuiPartSize:%x\n", info->part[i].uiPartSize);
printf("\t\t uiPartOffset:%x\n", info->part[i].uiPartOffset);
printf("\t\t uiDataLength:%x\n", info->part[i].uiDataLength);
printf("\t\tuiPartProperty:%x\n", info->part[i].uiPartProperty);
}
}
int RKPartition::checkPartsInfos()
{
if (mFWPartInfo.hdr.uiPartEntryCount != mPartInfo.hdr.uiPartEntryCount) {
printf("The number of partitions is inconsistent\n");
return -1;
}
for (int i = 0; i < mPartInfo.hdr.uiPartEntryCount; i++) {
if (strcmp((const char *)mFWPartInfo.part[i].szName,
(const char *)mPartInfo.part[i].szName) != 0) {
printf("The name of partitions is inconsistent\n");
return -1;
}
if (mFWPartInfo.part[i].uiDataLength > (mPartInfo.part[i].uiPartSize << 9)) {
printf("The szie of partitions is out of rang\n");
return -1;
}
}
return 0;
}
int RKPartition::checkKernelCRC(char *path, kernel_hdr *hdr)
{
int fd;
int readsize = 0;
struct_part_info info;
unsigned int kernel_offset;
unsigned int load_size;
unsigned char *kernel_data;
if (strcmp(path, imagepath) == 0) {
printf("####check Firmware kernel:\n");
memcpy(&info, &mFWPartInfo, sizeof(struct_part_info));
kernel_offset = getPartOffset_bytype(info, PART_KERNEL);
} else {
printf("\tcheck Storage kernel:\n");
memcpy(&info, &mPartInfo, sizeof(struct_part_info));
kernel_offset = 0;
}
printf("\t%s read kernel_addr %x \n", path, kernel_offset);
fd = open(path, O_RDONLY);
if (fd < 0) {
printf("%s open failed \n", path);
return -1;
}
lseek(fd, kernel_offset << 9, SEEK_SET);
if (read(fd, hdr, sizeof(kernel_hdr)) <= 0) {
printf("%s read hdr failed \n", path);
return -1;
}
load_size = hdr->loader_load_size;
kernel_data = (unsigned char *)malloc(load_size);
printf("\t%s read hdr->crc32 %x \n", path, hdr->crc32);
lseek(fd, (kernel_offset + 4) << 9, SEEK_SET);
readsize = readFile(fd, kernel_data, load_size);
if (readsize < 0) {
printf("%s read kernel_data failed \n", path);
return -1;
}
RKCRC* rkcrc = new RKCRC();
unsigned int crc32 = rkcrc->CRC_32(kernel_data, load_size);
delete rkcrc;
rkcrc = NULL;
printf("\t%s CRC_32 crc32 %x \n", path, crc32);
close(fd);
free(kernel_data);
return 0;
}
int RKPartition::checkImage(char *partname)
{
int index;
unsigned int size;
index = getPartIndex_byname(mPartInfo, partname);
if (index < 0) {
printf("checkimage getPartIndex_byname %s failed\n", partname);
return -1;
}
size = getFileSize(imagepath) >> 9;
if (size > mPartInfo.part[index].uiPartSize) {
printf("checkimage %s image size is too large error\n", partname);
return -1;
}
return 0;
}
int RKPartition::checkImage(int parttype)
{
int index;
unsigned int size;
index = getPartIndex_bytype(mPartInfo, parttype);
if (index < 0) {
printf("checkimage getPartIndex_bytype %d failed\n", parttype);
return -1;
}
size = getFileSize(imagepath) >> 9;
if (size > mPartInfo.part[index].uiPartSize) {
printf("checkimage type %s image size is too large error\n", parttype);
return -1;
}
return 0;
}
int RKPartition::fwPartitionInit()
{
if (getFwPartInfo(&mFWPartInfo) != 0) {
printf("getFwPart failed\n");
return -1;
}
if (checkPartsInfos() != 0) {
printf("check PartsInfos failed\n");
return -1;
}
if (checkKernelCRC(imagepath, &mFWKernelHdr) != 0) {
printf("check Firmware Kernel crc failed\n");
return -1;
}
return 0;
}
int RKPartition::partitionInit(char *partname)
{
if (checkImage(partname) != 0) {
printf("checkimage failed\n");
return -1;
}
return 0;
}
int RKPartition::partitionInit(int parttype)
{
if (checkImage(parttype) != 0) {
printf("checkimage failed\n");
return -1;
}
return 0;
}
int RKPartition::checkPartitions(int url_type)
{
int ret;
if (url_type == URL_TYPE_FIRMWARE)
ret = fwPartitionInit();
else if (url_type == URL_TYPE_KERNEL)
ret = partitionInit(PART_KERNEL);
else if (url_type == URL_TYPE_DTB)
ret = partitionInit(PART_DTB);
else if (url_type == URL_TYPE_USERDATA)
ret = partitionInit(PART_USER);
else
return -1;
return ret;
}
int RKPartition::RKPartition_init()
{
if (getStoragePartInfo(&mPartInfo) != 0) {
printf("get Storage Part failed\n");
return -1;
}
return 0;
}
int RKPartition::setImagePath(char *name)
{
if (name != NULL)
strcpy(imagepath, name);
return 0;
}
int RKPartition::setImageType(int type)
{
imagetype = type;
return 0;
}
unsigned int RKPartition::getPartOffset_bytype(struct_part_info info, uint32 type)
{
uint32 i;
if (info.hdr.uiFwTag == RK_PARTITION_TAG)
for (i = 0; i < info.hdr.uiPartEntryCount; i++)
if (info.part[i].emPartType == type) {
if (info.part[i].uiPartProperty == 0)
return info.part[i].uiPartOffset;
}
return 0;
}
int RKPartition::getPartIndex_bytype(struct_part_info info, uint32 type)
{
int i;
if (info.hdr.uiFwTag == RK_PARTITION_TAG)
for (i = 0; i < info.hdr.uiPartEntryCount; i++)
if (info.part[i].emPartType == type) {
if (info.part[i].uiPartProperty == 0)
return i;
}
return 0;
}
int RKPartition::getAPartIndex_bytype(struct_part_info info, uint32 type)
{
int i, cnt = 0;
int index[4] = { -1, -1, -1, -1};
if (info.hdr.uiFwTag == RK_PARTITION_TAG)
for (i = 0; i < info.hdr.uiPartEntryCount; i++)
if (info.part[i].emPartType == type) {
index[cnt++] = i;
}
if (index[1] < 0)
return index[0];
if (info.part[index[0]].uiPartProperty == 0)
return index[0];
else
return index[1];
}
int RKPartition::getBPartIndex_bytype(struct_part_info info, uint32 type)
{
int i, cnt = 0;
int index[4] = { -1, -1, -1, -1};
if (info.hdr.uiFwTag == RK_PARTITION_TAG)
for (i = 0; i < info.hdr.uiPartEntryCount; i++)
if (info.part[i].emPartType == type) {
index[cnt++] = i;
}
if (index[1] < 0)
return index[0];
if (info.part[index[0]].uiPartProperty == 0)
return index[1];
if (info.part[index[0]].uiPartProperty != 0)
return index[0];
}
unsigned int RKPartition::getPartOffset_byname(struct_part_info info, char *name)
{
uint32 i;
if (info.hdr.uiFwTag == RK_PARTITION_TAG)
for (i = 0; i < info.hdr.uiPartEntryCount; i++)
if (strcmp((const char *)info.part[i].szName, (const char *)name) == 0)
return info.part[i].uiPartOffset;
return 0;
}
int RKPartition::getPartIndex_byname(struct_part_info info, char *name)
{
int i;
if (info.hdr.uiFwTag == RK_PARTITION_TAG)
for (i = 0; i < info.hdr.uiPartEntryCount; i++)
if (strcmp((const char *)info.part[i].szName, (const char *)name) == 0)
return i;
return -1;
}
int RKPartition::updatePart(struct_setting_ini info)
{
int imagefd;
int storagefd;
int part_index = 0;
uint32 part_offset = 0;
uint32 part_datalen = 0;
kernel_hdr hdr;
uint32 rlen, wlen;
long rwremain;
int percent = 0, old_percent = 0;
unsigned char* ubuf = (unsigned char*)malloc(BUFFER_64K);
printf("####update part:%s dev:%s image:%s:\n",
info.szname, info.storge_path, imagepath);
if (imagetype == URL_TYPE_FIRMWARE) {
printf("\tupdate image get from firmware\n");
part_index = getPartIndex_bytype(mFWPartInfo, info.type);
if (part_index < 0) {
printf("update getPartIndex_bytype %s failed\n", info.szname);
return -1;
}
part_offset = mFWPartInfo.part[part_index].uiPartOffset;
part_datalen = mFWPartInfo.part[part_index].uiDataLength;
} else {
printf("\tupdate image get from part image\n");
part_offset = 0;
part_datalen = getFileSize(imagepath);
}
imagefd = open(imagepath, O_RDONLY);
if (imagefd < 0) {
printf("update open %s failed \n", imagepath);
return -1;
}
lseek(imagefd, part_offset << 9, SEEK_SET);
if ((storagefd = open(info.storge_path, O_RDWR)) < 0)
if (imagefd < 0) {
printf("update open %s failed \n", info.storge_path);
close(imagefd);
return -1;
}
if (RKdisp != NULL) {
RKdisp->RKDispClean();
RKdisp->DrawRect(box_rect);
sprintf(cap.str, "update %s...", info.szname);
cap.str_len = strlen(cap.str) * 8;
cap.y = 200;
cap.x = (RKdisp->fbinfo.vinfo.xres - cap.str_len) >> 1;
cap.color = 0xFFFFFFFF;
RKdisp->DrawString(cap);
}
rwremain = part_datalen;
while (rwremain > 0) {
if (RKdisp != NULL) {
percent = ((part_datalen - rwremain) * 100) / part_datalen;
for (int i = old_percent; i <= percent; i++) {
fill_rect.x = box_rect.x + (i / 10) * fill_rect.w;
RKdisp->DrawRect(fill_rect, 1, 1);
}
old_percent = percent;
}
//printf("\tupdate %s remain 0x%x byte\n", part_name, rwremain, percent);
//read
rlen = readFile(imagefd, ubuf, BUFFER_64K);
if (rlen < 0) {
printf("update read %s data failed \n", info.szname);
close(storagefd);
close(imagefd);
return -1;
}
//write
wlen = writeFile(storagefd, ubuf, rlen);
if (wlen != rlen) {
printf("update write %s data failed \n", info.storge_path);
close(storagefd);
close(imagefd);
return -1;
}
rwremain -= wlen;
fsync(storagefd);
sync();
}
if (RKdisp != NULL) {
RKdisp->RKDispClean();
sprintf(cap.str, "wait update %s sync", info.szname);
cap.str_len = strlen(cap.str) * 8;
cap.x = (RKdisp->fbinfo.vinfo.xres - cap.str_len) >> 1;
cap.y = 300;
RKdisp->DrawString(cap);
}
sleep(3);
fsync(storagefd);
sync();
close(storagefd);
close(imagefd);
free(ubuf);
if (info.type == PART_KERNEL) {
if (checkKernelCRC(info.storge_path, &hdr) != 0) {
printf("update %s crc32 failed \n", info.storge_path);
return -1;
}
}
#ifdef USE_EMMC
setPartBootPriority(&mPartInfo, info.type);
#endif
return 0;
}
RKPartition::RKPartition( RKDisplay *disp)
: RKdisp(disp)
{
if (RKdisp != NULL) {
box_rect.x = 372;
box_rect.y = 270;
box_rect.w = 280;
box_rect.h = 60;
box_rect.color = RKdisp->convColor(0xFFFFFFFF);
fill_rect.x = box_rect.x;
fill_rect.y = box_rect.y;
fill_rect.w = box_rect.w / 10;
fill_rect.h = box_rect.h;
fill_rect.color = RKdisp->convColor(0xFFFFFFFF);
}
}
RKPartition::~RKPartition()
{
}
int RKPartition::update(int parttype)
{
int index;
index = getBPartIndex_bytype(mPartInfo, parttype);
if (parttype == PART_USER || PART_BOOT == parttype) {
if (umount2(g_setting_ini[index].mount_path, MNT_FORCE | MNT_DETACH) < 0) {
printf("ERROR: umount2 %s fail\n", g_setting_ini[index].mount_path);
}
}
updatePart(g_setting_ini[index]);
return 0;
}
#if 0
int main(int argc, char const *argv[])
{
RKPartition* RKpart = new RKPartition();
//read partinfos and check fw
if (RKpart->RKPartition_init() != 0) {
printf("RKPartition_init failed\n");
return -1;
}
if (RKpart->update_kernel() != 0) {
printf("update_kernel failed\n");
return -1;
}
if (RKpart->update_userdata() != 0) {
printf("update_userdata failed\n");
return -1;
}
delete RKpart;
RKpart = NULL;
return 0;
}
#endif
<file_sep>/src/hal/hal_mixer/hal_mixer.h
/*
* =============================================================================
*
* Filename: tinyplay.h
*
* Description: rv1108音频接口
*
* Version: 1.0
* Created: 2019-06-26 15:44:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _TINYPLAY_H
#define _TINYPLAY_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
int rvMixerPlayOpen(int sample,int channle,int bit);
void rvMixerPlayClose(void);
int rvMixerPlayWrite(void *data,int size);
void rvMixerPlayInit(void);
int rvMixerCaptureOpen(int channel);
void rvMixerCaptureClose(void);
int rvMixerCaptureRead(void *data,int size,int channel);
void rvMixerCaptureInit(void);
int rvMixerSetPlayVolume(int value);
int rvMixerSetCaptureVolume(int value);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/protocol_hardcloud.c
/*
* =============================================================================
*
* Filename: protocol_hardcloud.c
*
* Description: 猫眼相关硬件云协议
*
* Version: 1.0
* Created: 2019-05-18 13:53:49
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <dirent.h>
#include <errno.h>
#include "cJSON.h"
#include "tcp_client.h"
#include "my_http.h"
#include "my_mqtt.h"
#include "json_dec.h"
#include "sql_handle.h"
#include "thread_helper.h"
#include "config.h"
#include "my_ntp.h"
#include "externfunc.h"
#include "my_dns.h"
#include "my_video.h"
#include "jpeg_enc_dec.h"
#include "debug.h"
#include "queue.h"
#include "sensor_detector.h"
#include "protocol.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define TOPIC_NUM 6
// 正式地址
#define HARD_COULD_API "https://iot.taichuan.net/v1"
// 测试地址
// #define HARD_COULD_API "http://84.internal.taichuan.net:8080/v1"
enum {
MODE_SEND_NEED_REPLY = 1,
MODE_SEND_NONEED_REPLY = 2,
MODE_REPLY = 4,
};
enum {
Sys_TestData = 1, // Server Send 测试数据指令 服务端发送测试内容到客户端 客户端必须立即将收到测试内容的data原封Return回来
Sys_UploadLog = 2, // Server Post 上传日志指令 要求客户端将异常等日志到服务器
Sys_Control = 3, // Server Send 控制(重启、启用、禁用))
CE_PostAwaken = 6000, // Server Post 无条件唤醒
CE_SendAwaken = 6001, // Server Send 无条件唤醒
CE_SetSelfIntercom = 6002, // Server Post 设置自身对讲账号
CE_SetTargetsIntercom = 6003,// Server Post 设置对方对讲账号
CE_GetIntercoms = 6004, // Client Send 获取所有对讲账号信息
CE_GetFaces = 6005, // Server Send 获取所有人脸信息
CE_SetFace = 6006, // Server Send 设置人脸
CE_RemoveFace = 6007, // Server Send 删除人脸
CE_Snap = 6008, // Server Send 抓拍
CE_GetConfig = 6009, // Server Send 获取猫眼配置
CE_SetConfig = 6010, // Server Send 设置猫眼配置
CE_Report = 6011, // Client Post 猫眼数据上报
CE_Reset = 6012, // Server Post 重置猫眼配置与数据
};
struct OPTS {
char client_id[32];
char username[32];
char password[32];
char host[16];
int port;
char pubTopic[64];
char platformUrl[64];
char ntp_server_ip[64];
char service_host[64];
int service_port;
};
struct DebugInfo{
int cmd;
char *info;
};
struct QueueList {
Queue *upload; // 上传七牛队列
Queue *report_capture; // 上报抓拍日志队列
Queue *report_alarm; // 上报报警队列
Queue *report_face; // 上报人脸记录队列
Queue *report_talk; // 上报通话记录队列
Queue *report_factory; // 上报恢复出厂设置队列
Queue *report_electric; // 上报电量队列
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
ProtocolHardcloud *protocol_hardcloud;
static MyHttp *http = NULL;
static MyMqtt *mqtt = NULL;
static int mqtt_connect_state;
static int heart_start = 0;
static int heart_end = 0;
static struct DebugInfo dbg_info[] = {
{Sys_TestData,"Sys_TestData"},
{Sys_UploadLog,"Sys_UploadLog"},
{Sys_Control,"Sys_Control"},
{CE_PostAwaken,"CE_PostAwaken"},
{CE_SendAwaken,"CE_SendAwaken"},
{CE_SetSelfIntercom,"CE_SetSelfIntercom"},
{CE_SetTargetsIntercom,"CE_SetTargetsIntercom"},
{CE_GetIntercoms,"CE_GetIntercoms"},
{CE_GetFaces,"CE_GetFaces"},
{CE_SetFace,"CE_SetFace"},
{CE_RemoveFace,"CE_RemoveFace"},
{CE_Snap,"CE_Snap"},
{CE_GetConfig,"CE_GetConfig"},
{CE_SetConfig,"CE_SetConfig"},
{CE_Report,"CE_Report"},
{CE_Reset,"CE_Reset"},
};
struct OPTS opts;
static char subTopic[TOPIC_NUM][100] = {{0,0}};
static int g_id = 0;
static char *qiniu_server_token = NULL;
static struct QueueList queue_list;
static void printProInfo(int cmd)
{
int i;
for (i=0; i<sizeof(dbg_info)/sizeof(struct DebugInfo); i++) {
if (cmd == dbg_info[i].cmd) {
printf("[%d,%s]\n", cmd,dbg_info[i].info);
return;
}
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief getTimestamp 获取当前时间戳
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static time_t getTimestamp(void)
{
struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec;
}
static cJSON * packData(int api,int mode,int id)
{
cJSON *root = cJSON_CreateObject();
cJSON_AddNumberToObject(root,"api",api);
cJSON_AddNumberToObject(root,"time",getTimestamp());
cJSON_AddNumberToObject(root,"mode",mode);
cJSON_AddNumberToObject(root,"id",id);
return root;
}
/* ---------------------------------------------------------------------------*/
/*
* @brief judgeHead 初始化JSON数据,
*
* @param data 数据 type:0表示整型,1表示字符型
*
* @returns state 为 true 时返回初始化的json指针 state 为 false 时返回空指针
*/
/* ---------------------------------------------------------------------------*/
static CjsonDec * judgeHead(char *data, char *state, int type)
{
CjsonDec *dec = cjsonDecCreate(data);
char *buff = NULL;
if (!dec) {
printf("json dec create fail!\n");
return NULL;
}
if(0 == type) {
int status = dec->getValueInt(dec, state);
if(0 != status) {
dec->print(dec);
dec->destroy(dec);
return NULL;
}
} else if(1 == type) {
dec->getValueChar(dec,state,&buff);
if (NULL == buff) {
printf("judgeHead getValueChar null!!\n");
dec->destroy(dec);
return NULL;
}
}
return dec;
}
static void mqttSubcribeSuccess(void* context)
{
}
static void mqttSubcribeFailure(void* context)
{
}
/* ---------------------------------------------------------------------------*/
/**
* @brief mqttConnectSuccess 链接成功后订阅相关主题
*
* @param context
*/
/* ---------------------------------------------------------------------------*/
static void mqttConnectSuccess(void* context)
{
int i;
for (i=0; i<TOPIC_NUM; i++) {
if (subTopic[i][0] != '\0')
mqtt->subcribe(subTopic[i], mqttSubcribeSuccess, mqttSubcribeFailure);
}
mqtt_connect_state = 1;
}
static void mqttConnectFailure(void* context)
{
printf("[%s]\n", __func__);
}
static void sysTestData(int api,int id,CjsonDec *dec)
{
char *send_buff = NULL;
if(dec->changeCurrentObj(dec,"body")) {
printf("change body fail\n");
return;
}
cJSON *data = dec->getValueObject(dec,"data");
cJSON *root = packData(api,MODE_REPLY,id);
cJSON_AddItemToObject(root,"body",data);
send_buff = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
mqtt->send(opts.pubTopic,strlen(send_buff),send_buff);
free(send_buff);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief ceSetSelfIntercom 设置本机对讲信息
*
* @param dec
*/
/* ---------------------------------------------------------------------------*/
static void ceSetSelfIntercom(CjsonDec *dec)
{
if(dec->changeCurrentObj(dec,"body")) {
printf("change body fail\n");
return;
}
char *user_id = NULL;
char *login_token = NULL;
char *nick_name = NULL;
int scope = 0 ;
dec->getValueChar(dec,"userId",&user_id);
dec->getValueChar(dec,"loginToken",&login_token);
dec->getValueChar(dec,"nickName",&nick_name);
scope = dec->getValueInt(dec,"scope");
sqlDeleteDeviceUseTypeNoBack(USER_TYPE_CATEYE);
sqlInsertUserInfo(user_id,login_token,nick_name,USER_TYPE_CATEYE,scope);
if (user_id)
free(user_id);
if (login_token)
free(login_token);
if (nick_name)
free(nick_name);
if (protocol_talk) {
protocol_talk->reload();
protocol_talk->reconnect();
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief ceSetTargetsIntercom 设置对方对讲账号
*
* @param dec
*/
/* ---------------------------------------------------------------------------*/
static void ceSetTargetsIntercom(CjsonDec *dec)
{
if(dec->changeCurrentObj(dec,"body")) {
printf("change body fail\n");
return;
}
char *user_id = NULL;
char *nick_name = NULL;
int scope = 0 ;
sqlDeleteDeviceUseTypeNoBack(USER_TYPE_OTHERS);
int size = dec->getArraySize(dec);
int i;
for (i=0; i<size; i++) {
user_id = NULL;
nick_name = NULL;
scope = 0 ;
dec->getArrayChar(dec,i,"userId",&user_id);
dec->getArrayChar(dec,i,"nickName",&nick_name);
scope = dec->getArrayInt(dec,i,"scope");
sqlInsertUserInfoNoBack(user_id,NULL,nick_name,USER_TYPE_OTHERS,scope);
if (user_id)
free(user_id);
if (nick_name)
free(nick_name);
}
sqlCheckBack();
if (protocol_talk) {
protocol_talk->reload();
protocol_talk->reconnect();
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief ceGetIntercoms 获取对讲信息
*
* @param dec
*/
/* ---------------------------------------------------------------------------*/
static void ceGetIntercoms(CjsonDec *dec)
{
if(dec->changeCurrentObj(dec,"body")) {
printf("change body fail\n");
return;
}
// 保存本机对讲信息
if(dec->changeCurrentObj(dec,"self")) {
printf("change self fail\n");
return;
}
char *user_id = NULL;
char *login_token = NULL;
char *nick_name = NULL;
int scope = 0 ;
dec->getValueChar(dec,"userId",&user_id);
dec->getValueChar(dec,"loginToken",&login_token);
dec->getValueChar(dec,"nickName",&nick_name);
scope = dec->getValueInt(dec,"scope");
sqlClearDeviceNoBack();
sqlInsertUserInfoNoBack(user_id,login_token,nick_name,USER_TYPE_CATEYE,scope);
if (user_id)
free(user_id);
if (login_token)
free(login_token);
if (nick_name)
free(nick_name);
// 保存对方对讲信息
dec->changeObjFront(dec); // 返回上一层
if(dec->changeCurrentObj(dec,"targets")) {
printf("targets self fail\n");
sqlCheckBack();
return;
}
int size = dec->getArraySize(dec);
int i;
for (i=0; i<size; i++) {
user_id = NULL;
nick_name = NULL;
scope = 0 ;
dec->getArrayChar(dec,i,"userId",&user_id);
dec->getArrayChar(dec,i,"nickName",&nick_name);
scope = dec->getArrayInt(dec,i,"scope");
sqlInsertUserInfoNoBack(user_id,NULL,nick_name,USER_TYPE_OTHERS,scope);
if (user_id)
free(user_id);
if (nick_name)
free(nick_name);
}
sqlCheckBack();
struct tm *tm_now = getTime();
g_config.timestamp = tm_now->tm_hour + tm_now->tm_mday * 24 + tm_now->tm_mon * 30 * 24;
ConfigSavePublic();
if (protocol_talk) {
protocol_talk->reload();
protocol_talk->reconnect();
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief ceGetFaces 获取人脸信息
*
* @param api
* @param id
* @param dec
*/
/* ---------------------------------------------------------------------------*/
static void ceGetFaces(int api,int id,CjsonDec *dec)
{
char *send_buff;
char user_id[32];
char nick_name[128];
char url[256];
cJSON *root = packData(api,MODE_REPLY,id);
cJSON *arry = cJSON_CreateArray();
sqlGetFaceStart();
while (1) {
memset(user_id,0,sizeof(user_id));
memset(nick_name,0,sizeof(nick_name));
memset(url,0,sizeof(url));
int ret = sqlGetFace(user_id,nick_name,url,NULL);
if (ret == 0)
break;
printf("id:%s,name:%s,url:%s\n", user_id,nick_name,url);
cJSON *obj = cJSON_CreateObject();
cJSON_AddStringToObject(obj,"id",user_id);
cJSON_AddStringToObject(obj,"nickName",nick_name);
cJSON_AddStringToObject(obj,"fileURL",url);
cJSON_AddItemToArray(arry, obj);
};
sqlGetFaceEnd();
cJSON_AddItemToObject(root,"body",arry);
send_buff = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
mqtt->send(opts.pubTopic,strlen(send_buff),send_buff);
free(send_buff);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief ceSetFace 设置人脸信息
*
* @param api
* @param id
* @param dec
*/
/* ---------------------------------------------------------------------------*/
static void ceSetFace(int api,int id,CjsonDec *dec)
{
char *send_buff;
cJSON *root;
int result = 0;
if(dec->changeCurrentObj(dec,"body")) {
printf("change body fail\n");
goto send_return;
}
char *user_id = NULL;
char *nick_name = NULL;
char *url = NULL;
int scope = 0 ;
dec->getValueChar(dec,"fileURL",&url);
dec->getValueChar(dec,"id",&user_id);
dec->getValueChar(dec,"nickName",&nick_name);
if (url) {
int w,h;
int yuv_len = 0;
char *buff_img = NULL;
unsigned char *yuv = NULL;
int leng = http->post(url,NULL,&buff_img);
jpegToYuv420sp((unsigned char *)buff_img, leng,&w,&h, &yuv, &yuv_len);
if (my_video)
if (my_video->faceRegist(yuv,w,h,user_id,nick_name,url) == 0)
result = 1;
if (buff_img)
free(buff_img);
if (yuv)
free(yuv);
}
if (url)
free(url);
if (user_id)
free(user_id);
if (nick_name)
free(nick_name);
send_return:
root = packData(api,MODE_REPLY,id);
if (result)
cJSON_AddStringToObject(root,"body","true");
else
cJSON_AddStringToObject(root,"body","false");
send_buff = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
mqtt->send(opts.pubTopic,strlen(send_buff),send_buff);
free(send_buff);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief ceRemoveFace 删除人脸信息
*
* @param api
* @param id
* @param dec
*/
/* ---------------------------------------------------------------------------*/
static void ceRemoveFace(int api,int id,CjsonDec *dec)
{
char *send_buff;
int result = 0;
cJSON *root;
if(dec->changeCurrentObj(dec,"body")) {
printf("change body fail\n");
goto send_return;
}
char *user_id = NULL;
dec->getValueChar(dec,"id",&user_id);
if (user_id) {
if (my_video)
my_video->faceDelete(user_id);
free(user_id);
}
result = 1;
send_return:
root = packData(api,MODE_REPLY,id);
if (result)
cJSON_AddStringToObject(root,"body","true");
else
cJSON_AddStringToObject(root,"body","false");
send_buff = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
mqtt->send(opts.pubTopic,strlen(send_buff),send_buff);
free(send_buff);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief mqttConnectCallBack 硬件云消息回调
*
* @param context
* @param topicName
* @param topicLen
* @param payload
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int mqttConnectCallBack(void* context, char* topicName, int topicLen, void* payload)
{
if (my_update->isUpdating(my_update))
return -1;
CjsonDec *dec = cjsonDecCreate((char*)payload);
if (NULL == dec) {
printf("dealWithSubscription cjsonDecCreate fail!\n");
return -1;
}
// dec->print(dec);
if (my_video)
my_video->delaySleepTime(1);
char send_buff[128] = {0};
int id = dec->getValueInt(dec, "id");
int mode = dec->getValueInt(dec, "mode");
int api= dec->getValueInt(dec, "api");
printProInfo(api);
switch (api)
{
case Sys_TestData :
sysTestData(api,id,dec);
break;
case Sys_UploadLog :
break;
case Sys_Control :
break;
case CE_PostAwaken :
break;
case CE_SendAwaken :
break;
case CE_SetSelfIntercom :
ceSetSelfIntercom(dec);
break;
case CE_SetTargetsIntercom :
ceSetTargetsIntercom(dec);
break;
case CE_GetIntercoms :
ceGetIntercoms(dec);
break;
case CE_GetFaces :
ceGetFaces(api,id,dec);
break;
case CE_SetFace :
ceSetFace(api,id,dec);
break;
case CE_RemoveFace :
ceRemoveFace(api,id,dec);
break;
case CE_Snap :
break;
case CE_GetConfig :
break;
case CE_SetConfig :
break;
case CE_Report :
break;
case CE_Reset :
break;
default:
break;
}
connect_end:
dec->destroy(dec);
return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief getIntercoms 获取所有对讲账号
*/
/* ---------------------------------------------------------------------------*/
static void getIntercoms(void)
{
struct tm *tm_now = getTime();
int timestamp_now = tm_now->tm_hour + tm_now->tm_mday * 24 + tm_now->tm_mon * 30 * 24;
printf("timestamp :now:%d,old:%d,div:%d\n",
timestamp_now, g_config.timestamp,timestamp_now - g_config.timestamp);
if (timestamp_now - g_config.timestamp <= 12) {
if (protocol_talk) {
protocol_talk->connect();
}
return;
}
char *send_buff;
cJSON *root = packData(CE_GetIntercoms,MODE_SEND_NEED_REPLY,++g_id);
cJSON_AddStringToObject(root,"body","");
send_buff = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
mqtt->send(opts.pubTopic,strlen(send_buff),send_buff);
free(send_buff);
}
static void ntpGetTimeCallback(void)
{
printf("sync net time\n");
}
static void waitConnectService(void)
{
while (1) {
if (opts.service_host[0] == 0 && heart_start) {
sleep(1);
continue;
}
return;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief initThread 初始化链接硬件云,mqtt链接方式,线程执行,直到链接上后退出
*
* @param arg
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static void* initThread(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
char *mqtt_server_content = NULL;
char url[128] = {0};
sprintf(url,"%s/Mqtt/GetSevice?num=%s",HARD_COULD_API,g_config.imei);
while (1) {
if (mqtt_server_content) {
free(mqtt_server_content);
mqtt_server_content = NULL;
}
http->post(url,NULL,&mqtt_server_content);
CjsonDec *dec = NULL;
char *buff = NULL;
// printf("[%s]\n",mqtt_server_content );
dec = judgeHead(mqtt_server_content,"code", 0);
if (!dec) {
printf("[%s,%d] judge head fail!\n", __func__,__LINE__);
goto retry;
}
if(0 != dec->changeCurrentObj(dec,"data"))
goto retry;
// dec->print(dec);
dec->getValueChar(dec,"ip",&buff);
if (!buff) {
printf("get ip [ip] null!!\n");
goto retry;
}
strcpy((char*)&opts.host, buff);
free(buff);
opts.port = dec->getValueInt(dec, "port");
strcpy((char*)&opts.client_id, g_config.imei);
strcpy((char*)&opts.username, g_config.imei);
strcpy((char*)&opts.password, g_config.hardcode);
if(0 != dec->changeCurrentObj(dec,"subTopics"))
goto retry;
int size = dec->getArraySize(dec);
int i;
for (i=0; i<size; i++) {
// 进入数组项
dec->getArrayChar(dec,i,NULL,&buff);
if (NULL == buff) {
printf("func:%s getArrayChar failed!!\n",__func__);
size = 0;
break;
} else {
strcpy(subTopic[i],buff);
printf("index:%d subTopic:%s\n",i,subTopic[i]);
}
free(buff);
}
dec->changeObjFront(dec);
dec->getValueChar(dec,"pubTopic",&buff);
if(NULL != buff) {
printf("publish topic %s\n", buff);
strcpy((char*)&opts.pubTopic, buff);
printf("opts publish Topic:%s\n",opts.pubTopic);
free(buff);
}
dec->getValueChar(dec,"ntpServer",&buff);
if(NULL != buff) {
printf("ntpServer: %s\n", buff);
strcpy(opts.ntp_server_ip, buff);
free(buff);
}
dec->getValueChar(dec,"platformURL",&buff);
if(NULL != buff) {
printf("platformURL: %s\n", buff);
strcpy((char*)&opts.platformUrl, buff);
free(buff);
}
if(0 != dec->changeCurrentObj(dec,"catEyeService"))
goto retry;
dec->getValueChar(dec,"host",&buff);
if(NULL != buff) {
printf("service_host: %s\n", buff);
strcpy((char*)&opts.service_host, buff);
free(buff);
}
opts.service_port = dec->getValueInt(dec,"port");
printf("service_port: %d\n", opts.service_port);
ntpTime(opts.ntp_server_ip,ntpGetTimeCallback);
sprintf(url, "%s:%d", opts.host, opts.port);
int ret = mqtt->connect(url,opts.client_id,
10,
opts.username,
opts.password,
mqttConnectCallBack,
mqttConnectSuccess,
mqttConnectFailure);
if (ret < 0)
goto retry;
if (dec)
dec->destroy(dec);
break;
retry:
if (dec)
dec->destroy(dec);
sleep(5);
}
if (mqtt_server_content) {
free(mqtt_server_content);
mqtt_server_content = NULL;
}
while (1) {
char *qiniu_server= NULL;
char url[128] = {0};
CjsonDec *dec = NULL;
sprintf(url,"%s/Storage/GetUploadToken?num=%s&code=%s&bucketName=%s",
HARD_COULD_API,
g_config.imei,
g_config.hardcode,
"tc-cat_eye");
int ret = http->post(url,NULL,&qiniu_server);
printf("[%d]%s\n",ret,url );
if (ret == 0)
goto retry_qiniu;
dec = cjsonDecCreate(qiniu_server);
if (!dec) {
printf("[%s,%d] get data fail!\n", __func__,__LINE__);
goto retry_qiniu;
}
dec->getValueChar(dec,"data",&qiniu_server_token);
if (!qiniu_server_token) {
printf("get qiniu token null!!\n");
goto retry_qiniu;
}
printf("qiniu token:%s\n", qiniu_server_token);
if (qiniu_server)
free(qiniu_server);
break;
retry_qiniu:
if (dec)
dec->destroy(dec);
if (qiniu_server)
free(qiniu_server);
sleep(1);
}
sleep(1);
return NULL;
}
static void writeSleepScript(char *dst_ip,int dst_port)
{
strcpy(g_config.wifi_lowpower.dst_ip,dst_ip);
sprintf(g_config.wifi_lowpower.dst_port,"%d",dst_port);
}
static void enableSleepMpde(void)
{
heart_start = 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief tcpHeartThread 硬件云心跳包
*
* @param arg
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static void* tcpHeartThread(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
char ip[16] = {0};
int connect_flag = 0;
char imei[32];
char imei_len[8];
char gateway[16];
int send_interval = 0;
// 等待连接上服务器
waitConnectService();
dnsGetIp(opts.service_host,ip);
writeSleepScript(ip,opts.service_port);
while (heart_start) {
if (connect_flag == 1 && send_interval < 30) {
send_interval++;
char tcp_rec[64] = {0};
int len = tcp_client->RecvBuffer(tcp_client,tcp_rec,sizeof(tcp_rec),1000);
if (strcmp(tcp_rec,"AwakenAsync")== 0) {
if (my_video)
my_video->delaySleepTime(1);
}
goto loop_heart;
}
send_interval = 0;
if (tcp_client->Connect(tcp_client,ip,opts.service_port,5000) < 0){
printf("connect fail,:%s,%d\n",ip,opts.service_port);
goto loop_heart;
} else {
connect_flag = 1;
tcp_client->SendBuffer(tcp_client,g_config.imei,strlen(g_config.imei));
}
loop_heart:
sleep(1);
}
tcp_client->DisConnect(tcp_client);
getLocalIP(g_config.wifi_lowpower.local_ip,gateway);
getGateWayMac(gateway,g_config.wifi_lowpower.dst_mac);
sprintf(imei,"\"%s\"",g_config.imei);
sprintf(imei_len,"%ld",strlen(g_config.imei));
#if 1
excuteCmd("dhd_priv","wl","tcpka_conn_add","1",
g_config.wifi_lowpower.dst_mac,
g_config.wifi_lowpower.local_ip,
g_config.wifi_lowpower.dst_ip,
"0","1223",
g_config.wifi_lowpower.dst_port,
"1","0","1024","1062046","2130463","1",imei_len, imei,
NULL);
sleep(1);
#else
excuteCmd("dhd_priv","wl","tcpka_conn_add","1",
"6C:4B:90:0C:C9:9B",
"10.0.2.92",
"10.0.0.38",
"0","1223",
"1221",
"1","0","1024","1062046","2130463","1","14","CE191023000139",NULL);
#endif
excuteCmd("dhd_priv","wl","tcpka_conn_enable","1","1","10","10","10",NULL);
sleep(1);
excuteCmd("dhd_priv","setsuspendmode","1",NULL);
sleep(1);
protocol_singlechip->cmdSleep();
return NULL;
}
static void* getIntercomsThread(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
while (1) {
if (mqtt_connect_state) {
getIntercoms();
break;
}
sleep(1);
}
return NULL;
}
static void* threadUpload(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
UpLoadData up_data;
char *qiniu_upload= NULL;
DIR *dir;
struct dirent *dirp;
while (!qiniu_server_token) {
sleep(1);
}
while (1) {
if (queue_list.upload) {
queue_list.upload->get(queue_list.upload,&up_data);
} else {
sleep(1);
continue;
}
char file_name[64] = {0};
sprintf(file_name,"%s_%lld",g_config.imei,up_data.picture_id);
int file_len = strlen(file_name);
if((dir=opendir(up_data.file_path)) == NULL) {
printf("Open File %s Error %s\n",up_data.file_path,strerror(errno));
return 0;
}
while((dirp=readdir(dir)) != NULL) {
if ( (strcmp(".",dirp->d_name) == 0)
|| (strcmp("..",dirp->d_name) == 0)
|| strncmp(file_name,dirp->d_name,file_len)) {
continue;
}
char buf[64];
sprintf(buf,"%s%s",up_data.file_path,dirp->d_name);
printf("[%s]%s\n",__func__,buf);
if (GetFileSize(buf) == 0) {
printf("[%s]file size == 0\n",__func__);
continue;
}
http->qiniuUpload("http://upload-z2.qiniup.com",
NULL,qiniu_server_token,
buf,
dirp->d_name,
&qiniu_upload);
if (qiniu_upload) {
printf("%s\n",qiniu_upload);
free(qiniu_upload);
}
if (remove(buf) < 0) {
printf("remove error:%s\n",strerror(errno));
} else {
printf("remove:%s\n",buf);
}
}
sqlCheckBack();
closedir(dir);
}
return NULL;
}
static void uploadPic(char *path,uint64_t pic_id)
{
printf("[%s]pic_id:%lld\n", __func__,pic_id);
if (pic_id == 0)
return;
UpLoadData up_data;
strcpy(up_data.file_path,path);
up_data.picture_id = pic_id;
if (!queue_list.upload) {
queue_list.upload = queueCreate("upload",QUEUE_BLOCK,sizeof(UpLoadData));
}
queue_list.upload->post(queue_list.upload,&up_data);
}
static void* threadReportCapture(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
uint64_t picture_id = 0;
char date[64] = {0};
int i;
char *send_buff;
waitConnectService();
while (1) {
if (queue_list.report_capture) {
queue_list.report_capture->get(queue_list.report_capture,&picture_id);
} else {
sleep(1);
continue;
}
int ret = sqlGetCapInfo(picture_id,date);
// 封装jcson信息
cJSON *root = packData(CE_Report,MODE_SEND_NONEED_REPLY,++g_id);
cJSON *obj_body = cJSON_CreateObject();
cJSON_AddStringToObject(obj_body,"dataType","capture");
cJSON *arry_pic = cJSON_CreateArray();
cJSON *arry_record = cJSON_CreateArray();
if (ret) {
int count = sqlGetPicInfoStart(picture_id);
for (i=0; i<count; i++) {
char url[128] = {0};
cJSON *obj = cJSON_CreateObject();
sqlGetPicInfos(url);
cJSON_AddStringToObject(obj,"url",url);
cJSON_AddItemToArray(arry_pic, obj);
}
sqlGetPicInfoEnd();
count = sqlGetRecordInfoStart(picture_id);
for (i=0; i<count; i++) {
char url[128] = {0};
cJSON *obj = cJSON_CreateObject();
sqlGetRecordInfos(url);
cJSON_AddStringToObject(obj,"url",url);
cJSON_AddItemToArray(arry_record, obj);
}
sqlGetRecordInfoEnd();
}
cJSON *obj_data = cJSON_CreateObject();
cJSON_AddStringToObject(obj_data,"date",date);
cJSON_AddItemToObject(obj_data,"picture",arry_pic);
cJSON_AddItemToObject(obj_data,"record",arry_record);
cJSON_AddItemToObject(obj_body,"data",obj_data);
cJSON_AddItemToObject(root,"body",obj_body);
send_buff = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
mqtt->send(opts.pubTopic,strlen(send_buff),send_buff);
free(send_buff);
}
return NULL;
}
static void reportCapture(uint64_t pic_id)
{
uint64_t data = pic_id;
if (!queue_list.report_capture)
queue_list.report_capture = queueCreate("re_cap",QUEUE_BLOCK,sizeof(uint64_t));
queue_list.report_capture->post(queue_list.report_capture,&data);
}
static void* threadReportAlarm(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
ReportAlarmData alarm_data;
int i;
char *send_buff;
waitConnectService();
while (1) {
if (queue_list.report_alarm) {
queue_list.report_alarm->get(queue_list.report_alarm,&alarm_data);
} else {
sleep(1);
continue;
}
// 封装jcson信息
cJSON *root = packData(CE_Report,MODE_SEND_NONEED_REPLY,++g_id);
cJSON *obj_body = cJSON_CreateObject();
cJSON_AddStringToObject(obj_body,"dataType","alarmRecord");
cJSON *obj_data = cJSON_CreateObject();
cJSON_AddStringToObject(obj_data,"date",alarm_data.date);
cJSON_AddNumberToObject(obj_data,"type",alarm_data.type);
if (alarm_data.has_people)
cJSON_AddTrueToObject(obj_data,"hasPeople");
else
cJSON_AddFalseToObject(obj_data,"hasPeople");
cJSON_AddNumberToObject(obj_data,"sex",alarm_data.sex);
cJSON_AddNumberToObject(obj_data,"age",alarm_data.age);
cJSON *arry = cJSON_CreateArray();
int count = sqlGetPicInfoStart(alarm_data.picture_id);
for (i=0; i<count; i++) {
char url[128] = {0};
cJSON *obj = cJSON_CreateObject();
sqlGetPicInfos(url);
cJSON_AddStringToObject(obj,"url",url);
cJSON_AddItemToArray(arry, obj);
}
sqlGetPicInfoEnd();
cJSON_AddItemToObject(obj_data,"picture",arry);
cJSON_AddItemToObject(obj_body,"data",obj_data);
cJSON_AddItemToObject(root,"body",obj_body);
send_buff = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
mqtt->send(opts.pubTopic,strlen(send_buff),send_buff);
free(send_buff);
}
return NULL;
}
static void reportAlarm(ReportAlarmData *data)
{
if (!queue_list.report_alarm)
queue_list.report_alarm = queueCreate("re_alarm",QUEUE_BLOCK,sizeof(ReportAlarmData));
queue_list.report_alarm->post(queue_list.report_alarm,data);
}
static void* threadReportFace(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
ReportFaceData face_data;
int i;
char *send_buff;
waitConnectService();
while (1) {
if (queue_list.report_face) {
queue_list.report_face->get(queue_list.report_face,&face_data);
} else {
sleep(1);
continue;
}
// 封装jcson信息
cJSON *root = packData(CE_Report,MODE_SEND_NONEED_REPLY,++g_id);
cJSON *obj_body = cJSON_CreateObject();
cJSON_AddStringToObject(obj_body,"dataType","faceRecognitionRecord");
cJSON *obj_data = cJSON_CreateObject();
cJSON_AddStringToObject(obj_data,"date",face_data.date);
cJSON_AddStringToObject(obj_data,"faceId",face_data.user_id);
cJSON *obj_face_info = cJSON_CreateObject();
cJSON_AddStringToObject(obj_face_info,"nickName",face_data.nick_name);
cJSON_AddItemToObject(obj_data,"faceInfo",obj_face_info);
int count = sqlGetPicInfoStart(face_data.picture_id);
if (count) {
char url[128] = {0};
sqlGetPicInfos(url);
cJSON_AddStringToObject(obj_data,"picture",url);
}
sqlGetPicInfoEnd();
cJSON_AddItemToObject(obj_body,"data",obj_data);
cJSON_AddItemToObject(root,"body",obj_body);
send_buff = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
mqtt->send(opts.pubTopic,strlen(send_buff),send_buff);
free(send_buff);
}
return NULL;
}
static void reportFace(ReportFaceData *data)
{
if (!queue_list.report_face)
queue_list.report_face = queueCreate("re_face",QUEUE_BLOCK,sizeof(ReportFaceData));
queue_list.report_face->post(queue_list.report_face,data);
}
static void* threadReportTalk(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
ReportTalkData talk_data;
int i;
char *send_buff;
waitConnectService();
while (1) {
if (queue_list.report_talk) {
queue_list.report_talk->get(queue_list.report_talk,&talk_data);
} else {
sleep(1);
continue;
}
// 封装jcson信息
cJSON *root = packData(CE_Report,MODE_SEND_NONEED_REPLY,++g_id);
cJSON *obj_body = cJSON_CreateObject();
cJSON_AddStringToObject(obj_body,"dataType","callRecord");
cJSON *obj_data = cJSON_CreateObject();
cJSON_AddStringToObject(obj_data,"date",talk_data.date);
cJSON_AddStringToObject(obj_data,"people",talk_data.nick_name);
cJSON_AddNumberToObject(obj_data,"callDir",talk_data.call_dir);
if (talk_data.answered)
cJSON_AddTrueToObject(obj_data,"autoAnswer");
else
cJSON_AddFalseToObject(obj_data,"autoAnswer");
cJSON_AddNumberToObject(obj_data,"talkTime",talk_data.talk_time);
cJSON *arry_pic = cJSON_CreateArray();
cJSON *arry_record = cJSON_CreateArray();
int count = sqlGetPicInfoStart(talk_data.picture_id);
for (i=0; i<count; i++) {
char url[128] = {0};
cJSON *obj = cJSON_CreateObject();
sqlGetPicInfos(url);
cJSON_AddStringToObject(obj,"url",url);
cJSON_AddItemToArray(arry_pic, obj);
}
sqlGetPicInfoEnd();
count = sqlGetRecordInfoStart(talk_data.picture_id);
for (i=0; i<count; i++) {
char url[128] = {0};
cJSON *obj = cJSON_CreateObject();
sqlGetRecordInfos(url);
cJSON_AddStringToObject(obj,"url",url);
cJSON_AddItemToArray(arry_record, obj);
}
sqlGetRecordInfoEnd();
cJSON_AddItemToObject(obj_data,"picture",arry_pic);
cJSON_AddItemToObject(obj_data,"record",arry_record);
cJSON_AddItemToObject(obj_body,"data",obj_data);
cJSON_AddItemToObject(root,"body",obj_body);
send_buff = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
mqtt->send(opts.pubTopic,strlen(send_buff),send_buff);
free(send_buff);
}
return NULL;
}
static void reportTalk(ReportTalkData *data)
{
if (!queue_list.report_talk)
queue_list.report_talk = queueCreate("re_talk",QUEUE_BLOCK,sizeof(ReportTalkData));
queue_list.report_talk->post(queue_list.report_talk,data);
}
static void* threadReportFactory(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
ReportFactory factory_data;
int i;
char *send_buff;
waitConnectService();
while (1) {
if (queue_list.report_factory) {
queue_list.report_factory->get(queue_list.report_factory,&factory_data);
} else {
sleep(1);
continue;
}
// 封装jcson信息
cJSON *root = packData(CE_Report,MODE_SEND_NONEED_REPLY,++g_id);
cJSON *obj_body = cJSON_CreateObject();
cJSON_AddStringToObject(obj_body,"dataType","factoryReset");
cJSON *obj_data = cJSON_CreateObject();
cJSON_AddStringToObject(obj_data,"date",factory_data.date);
cJSON_AddItemToObject(obj_body,"data",obj_data);
cJSON_AddItemToObject(root,"body",obj_body);
send_buff = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
mqtt->send(opts.pubTopic,strlen(send_buff),send_buff);
free(send_buff);
}
return NULL;
}
static void reportFactory(ReportFactory *data)
{
if (!queue_list.report_factory)
queue_list.report_factory = queueCreate("re_factory",QUEUE_BLOCK,sizeof(ReportFactory));
queue_list.report_factory->post(queue_list.report_factory,data);
}
static void* threadReportElectric(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
ReportElectric electric_data;
int i;
char *send_buff;
waitConnectService();
while (1) {
if (queue_list.report_electric) {
queue_list.report_electric->get(queue_list.report_electric,&electric_data);
} else {
sleep(1);
continue;
}
// 封装jcson信息
cJSON *root = packData(CE_Report,MODE_SEND_NONEED_REPLY,++g_id);
cJSON *obj_body = cJSON_CreateObject();
cJSON_AddStringToObject(obj_body,"dataType","battery");
cJSON *obj_data = cJSON_CreateObject();
cJSON_AddStringToObject(obj_data,"date",electric_data.date);
cJSON_AddNumberToObject(obj_data,"electric",electric_data.value);
cJSON_AddItemToObject(obj_body,"data",obj_data);
cJSON_AddItemToObject(root,"body",obj_body);
send_buff = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
mqtt->send(opts.pubTopic,strlen(send_buff),send_buff);
free(send_buff);
}
return NULL;
}
static void reportElectric(ReportElectric *data)
{
if (!queue_list.report_electric)
queue_list.report_electric = queueCreate("re_factory",QUEUE_BLOCK,sizeof(ReportElectric));
queue_list.report_electric->post(queue_list.report_electric,data);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief registHardCloud 注册硬件云
*/
/* ---------------------------------------------------------------------------*/
void registHardCloud(void)
{
ReportElectric electric_data;
protocol_hardcloud = (ProtocolHardcloud *) calloc(1,sizeof(ProtocolHardcloud));
protocol_hardcloud->uploadPic = uploadPic;
protocol_hardcloud->reportCapture = reportCapture;
protocol_hardcloud->reportAlarm = reportAlarm;
protocol_hardcloud->reportFace= reportFace;
protocol_hardcloud->reportTalk= reportTalk;
protocol_hardcloud->reportFactory= reportFactory;
protocol_hardcloud->reportElectric= reportElectric;
protocol_hardcloud->enableSleepMpde = enableSleepMpde;
mqtt_connect_state = 0;
tcpClientInit();
http = myHttpCreate();
mqtt = myMqttCreate();
heart_start = 1;
createThread(initThread,NULL);
createThread(tcpHeartThread,NULL);
createThread(getIntercomsThread,NULL);
createThread(threadUpload,NULL);
createThread(threadReportCapture,NULL);
createThread(threadReportAlarm,NULL);
createThread(threadReportFace,NULL);
createThread(threadReportTalk,NULL);
createThread(threadReportFactory,NULL);
createThread(threadReportElectric,NULL);
ntpEnable(g_config.auto_sync_time);
getDate(electric_data.date,sizeof(electric_data.date));
electric_data.value = sensor->getElePower();
protocol_hardcloud->reportElectric(&electric_data);
}
<file_sep>/src/drivers/my_mixer.c
/*
* =====================================================================================
*
* Filename: Mixer.c
*
* Description: 混音器接口处理
*
* Version: 1.0
* Created: 2015-12-21 15:28:18
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
/* ----------------------------------------------------------------*
* include head files
*-----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/soundcard.h>
#include <sys/types.h>
#include <sys/poll.h>
#include <pthread.h>
#include <math.h>
#include <signal.h>
#include <sys/time.h>
#include <time.h>
#include <errno.h>
#include "hal_mixer.h"
#include "my_mixer.h"
#include "externfunc.h"
/* ----------------------------------------------------------------*
* extern variables declare
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*
* internal functions declare
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*
* macro define
*-----------------------------------------------------------------*/
#if DBG_MYMIXER > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define MAXMIXER 3
typedef struct _TMixerPriv
{
pthread_mutex_t mutex;
void *aec_buf;
int Inited; //是否初始化成功
int audiofp; //打开声卡驱动 放音
int mixer_fd; //混音器句柄 喇叭
int audiofp1; //打开声卡驱动 录音
int mixer_fd1; //混音器句柄 咪头
int channle; // 声道数量
unsigned int MinVolume; //最小音量
unsigned int MaxVolume; //最大音量
unsigned int MicVolume; //MIC音量
int PlayVolume; //播放音量
int bSlience; //是否静音 1静音 0非静音
}TMixerPriv;
/* ----------------------------------------------------------------*
* variables define
*-----------------------------------------------------------------*/
TMixer *my_mixer = NULL;
static int MonoToStereo(const void *pSrc,int Size,void *pDst)
{
const short *p1 = (const short*)pSrc;
short *p2 = (short *)pDst;
int i = Size/2;
do {
*p2++ = *p1;
*p2++ = *p1++;
}while(--i);
return Size*2;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerOpen 打开放音声卡
*
* @param This
* @param Sample 设置采样率
* @param ch 设置通道
*
* @returns 0失败
*/
/* ----------------------------------------------------------------*/
static int mixerOpen(TMixer *This,int sample,int ch)
{
pthread_mutex_lock (&This->Priv->mutex);
int ret = 0;
static int err_times ;
if (This->Priv->audiofp > 0) {
goto mixer_open_end;
}
err_times = 0;
This->Priv->channle = ch;
//打开声卡放音句柄 确保视频文件停止播放
do {
printf("mixer open sample:%d,ch:%d\n", sample,ch);
This->Priv->audiofp = rvMixerPlayOpen(sample,ch,16);
if (This->Priv->audiofp > 0)
break;
usleep(100000);
} while(1);
mixer_open_end:
This->Priv->Inited = 1;
ret = This->Priv->audiofp;
pthread_mutex_unlock (&This->Priv->mutex);
return ret;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerClose 关闭放音设备
*
* @param This
* @param Handle 设备句柄
*
* @returns
*/
/* ----------------------------------------------------------------*/
static int mixerClose(TMixer *This,int *Handle)
{
pthread_mutex_lock (&This->Priv->mutex);
rvMixerPlayClose();
This->Priv->Inited = 0;
*Handle = This->Priv->audiofp = -1;
pthread_mutex_unlock (&This->Priv->mutex);
return 0;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerRead 从声卡读声音,录音
*
* @param This
* @param pBuffer 保存录音数据
* @param Size 一次读取字节大小
*
* @returns 实际读取字节数据
*/
/* ----------------------------------------------------------------*/
static int mixerRead(TMixer *This,void *pBuffer,int Size,int channel)
{
int ret = 0;
if (This->Priv->audiofp1 == -1)
This->Priv->audiofp1 = rvMixerCaptureOpen(channel);
if (This->Priv->audiofp1 != -1) {
ret = rvMixerCaptureRead(pBuffer,Size,channel);
}
return ret;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerReadBuffer 从声卡读声音,录音
*
* @param This
* @param AudioBuf 保存录音数据
* @param NeedSize 一次读取字节大小
*
* @returns 实际读取字节数据
*/
/* ----------------------------------------------------------------*/
static int mixerReadBuffer(TMixer *This, void *AudioBuf, int NeedSize,int channel)
{
int RealSize = This->Read(This,AudioBuf,NeedSize,channel);
return RealSize;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerWrite 写声音缓存
*
* @param This
* @param Handle 通道
* @param pBuffer 数据
* @param Size 大小
*
* @returns
*/
/* ----------------------------------------------------------------*/
static int mixerWrite(TMixer *This,int Handle,const void *pBuffer,int Size)
{
// printf("[%s]init:%d,handle:%d,size:%d\n",
// __FUNCTION__,
// This->Priv->Inited,Handle,Size);
int ret = 0;
if(This->Priv->Inited == 0 ) {
goto mixer_write_end;
}
if(Handle<1) {
goto mixer_write_end;
}
if(Size<10) {
ret = Size;
return Size;
}
ret = rvMixerPlayWrite((void *)pBuffer,Size);
mixer_write_end:
return ret;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerWriteBuffer 写声音缓存块
*
* @param This
* @param Handle 通道
* @param pBuffer 数据
* @param Size 大小
*
* @returns
*/
/* ----------------------------------------------------------------*/
static int mixerWriteBuffer(TMixer *This,int Handle,const void *pBuffer,int Size)
{
DBG_P("[%s]\n",__FUNCTION__);
const char *pBuf = (const char*)pBuffer;
int LeaveSize = Size;
while(LeaveSize) {
int WriteSize = This->Write(This,Handle,pBuf,LeaveSize);
if(WriteSize <= 0) {
break;
}
pBuf += WriteSize;
LeaveSize -= WriteSize;
}
return Size;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerGetVolume 获得音量
*
* @param This
* @param type 音量类型 0放音 1录音
*
* @returns 音量值
*/
/* ----------------------------------------------------------------*/
static int mixerGetVolume(struct _TMixer *This,int type)
{
if (type) {
return This->Priv->MicVolume;
} else {
return This->Priv->PlayVolume;
}
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerSetVolume 设置音量
*
* @param This
* @param Volume 音量
* @param type 混音器类型 0放音 1录音
*
* @returns 设置结果
*/
/* ----------------------------------------------------------------*/
static int mixerSetVolume(struct _TMixer *This,int type,int Volume)
{
// pthread_mutex_lock (&This->Priv->mutex);
int Value,buf;
int ret = 0;
if(Volume<0) {
Volume = 0;
DBG_P("Set volume value %d wrong,set zero\n",Volume);
}
if(Volume>100) {
Volume = 100;
DBG_P("Set volume value %d wrong,set 100\n",Volume);
}
Value = This->Priv->MinVolume + Volume*(This->Priv->MaxVolume-This->Priv->MinVolume)/100;
DBG_P("Volume Value:%d\n",Value);
buf = Value;
Value <<= 8;
Value |= buf;
if (type) {
if(rvMixerSetPlayVolume(Value) == EXIT_FAILURE) {
fprintf(stdout,"Set Volume %d ,%s\n", Value,strerror(errno));
ret = -2;
goto mixer_set_voluem_end;
}
This->Priv->PlayVolume = Volume;
} else {
if(rvMixerSetCaptureVolume(Value) == EXIT_FAILURE) {
fprintf(stdout,"Set Volume %d ,%s\n", Value,strerror(errno));
ret = -2;
goto mixer_set_voluem_end;
}
This->Priv->MicVolume = Volume;
}
mixer_set_voluem_end:
// pthread_mutex_unlock (&This->Priv->mutex);
return ret;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerSetVolumeEx 通过外部应用程序设置音量
*
* @param This
* @param Volume 音量
*
* @returns
*/
/* ----------------------------------------------------------------*/
static int mixerSetVolumeEx(struct _TMixer *This,int Volume)
{
if (This->Priv->PlayVolume == Volume)
return 0;
This->Priv->PlayVolume = Volume;
setSysVolume(Volume);
return 0;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerInitVolume 初始化音量
*
* @param This
* @param Volume 音量
* @param bSlience 0非静音 1静音
*
*/
/* ----------------------------------------------------------------*/
static void mixerInitVolume(struct _TMixer *This,int Volume,int bSlience)
{
This->SetVolume(This,Volume,1);
This->Priv->bSlience = bSlience;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerSetSlience 设置静音
*
* @param This
* @param bSlience 1静音,0非静音
*/
/* ----------------------------------------------------------------*/
static void mixerSetSlience(struct _TMixer *This,int bSlience)
{
This->Priv->bSlience = bSlience;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerGetSlience 返回静音状态
*
* @param This
*
* @returns 1静音,0非静音
*/
/* ----------------------------------------------------------------*/
static int mixerGetSlience(struct _TMixer *This)
{
return This->Priv->bSlience;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerClearRecBuffer 清除声音录音缓冲区
*
* @param This
*
* @returns
*/
/* ----------------------------------------------------------------*/
static void mixerClearRecBuffer(TMixer *This)
{
return;
int i;
int buffersize = 1024;
char *pBuf;
int ret;
if (This->Priv->audiofp1 == -1) {
return;
}
pBuf = (char *)malloc(buffersize );
if(pBuf && buffersize > 0) {
for(i=0; i<8; i++) {
memset(pBuf,0,buffersize);
ret = This->Read(This,pBuf,buffersize,1);
printf("ClearRecBuffer[%d]Rec buffersize :%d,real:%d\n", i,buffersize,ret);
}
}
free(pBuf);
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerClearPlayBuffer 清除声音放音缓冲区
*
* @param This
*
* @returns
*/
/* ----------------------------------------------------------------*/
static void mixerClearPlayBuffer(TMixer *This)
{
// PcmOut_resetAll();
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerInitPlayAndRec 初始化录音和放音
*
* @param This
* @param handle 返回声卡句柄
* @param type ENUM_MIXER_CLEAR_PLAY_BUFFER 清除放音句柄
* ENUM_MIXER_CLEAR_REC_BUFFER 清除录音句柄
*/
/* ----------------------------------------------------------------*/
static void mixerInitPlayAndRec(TMixer *This,int *handle,int sample,int channle)
{
int fp;
fp = This->Open(This,FMT8K,channle);
if (fp <= 0) {
return;
}
// anykaCaptureStart(1);
This->ClearRecBuffer(This);
// This->ClearPlayBuffer(This);
*handle = fp;
}
static void mixerInitPlay8K(TMixer *This,int *handle)
{
int fp;
fp = This->Open(This,FMT8K,1);
if (fp <= 0) {
return;
}
// anykaCaptureStart(0);
*handle = fp;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerDeInitPlay 清除放音缓存,释放放音设备
*
* @param This
* @param handle 放音设备句柄
*/
/* ----------------------------------------------------------------*/
static void mixerDeInitPlay(TMixer *This,int *handle)
{
if (This->Priv->audiofp1 < 0)
return;
rvMixerCaptureClose();
This->Priv->audiofp1 = -1;
This->ClearPlayBuffer(This);
This->Close(This, handle);
}
static void mixerDeInitPlay8K(TMixer *This,int *handle)
{
This->ClearPlayBuffer(This);
This->Close(This, handle);
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerDestroy 销毁混音器,释放资源
*
* @param This
*/
/* ----------------------------------------------------------------*/
static void mixerDestroy(TMixer *This)
{
if(This->Priv->audiofp!=-1)
close(This->Priv->audiofp);
if(This->Priv->mixer_fd!=-1)
close(This->Priv->mixer_fd);
if(This->Priv->audiofp1!=-1)
close(This->Priv->audiofp1);
if(This->Priv->mixer_fd1!=-1)
close(This->Priv->mixer_fd1);
free(This->Priv);
free(This);
This = NULL;
}
/* ----------------------------------------------------------------*/
/**
* @brief mixerCreate 创建混音器接口
*
* @returns 混音器指针
*/
/* ----------------------------------------------------------------*/
TMixer* mixerCreate(void)
{
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
TMixer *This = (TMixer *)malloc(sizeof(TMixer));
memset(This,0,sizeof(TMixer));
This->Priv = (TMixerPriv *)malloc(sizeof(TMixerPriv));
memset(This->Priv,0,sizeof(TMixerPriv));
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&This->Priv->mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
rvMixerPlayInit();
rvMixerCaptureInit();
This->Priv->Inited = 0;
This->Priv->audiofp = -1;
This->Priv->audiofp1 = -1;
This->Destroy = mixerDestroy;
This->Open = mixerOpen;
This->Close = mixerClose;
This->Read = mixerRead;
This->ReadBuf = mixerReadBuffer;
This->Write = mixerWrite;
This->WriteBuffer = mixerWriteBuffer;
This->InitVolume = mixerInitVolume;
This->GetVolume = mixerGetVolume;
This->SetVolume = mixerSetVolume;
This->SetVolumeEx = mixerSetVolumeEx;
This->SetSlience = mixerSetSlience;
This->GetSlience = mixerGetSlience;
This->ClearRecBuffer = mixerClearRecBuffer;
This->ClearPlayBuffer = mixerClearPlayBuffer;
This->InitPlayAndRec = mixerInitPlayAndRec;
This->InitPlay8K = mixerInitPlay8K;
This->DeInitPlay = mixerDeInitPlay;
This->DeInitPlay8K = mixerDeInitPlay8K;
return This;
}
void myMixerInit(void)
{
my_mixer = mixerCreate();
}
<file_sep>/src/app/media_muxer.c
/*
* =============================================================================
*
* Filename: media_muxer.c
*
* Description: 音视频封装接口
*
* Version: 1.0
* Created: 2019-09-12 10:15:23
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include "avilib/avilib.h"
#include "mp4_muxer/mp4_muxer.h"
#include "media_muxer.h"
#include "externfunc.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define FOURCC uint32_t
#pragma pack (1)
typedef struct tagMYBITMAPINFOHEADER {
uint64_t biSize;
uint32_t biWidth;
uint32_t biHeight;
uint32_t biPlanes;
uint32_t biBitCount;
uint64_t biCompression;
uint64_t biSizeImage;
uint32_t biXPelsPerMeter;
uint32_t biYPelsPerMeter;
uint64_t biClrUsed;
uint64_t biClrImportant;
} MYBITMAPINFOHEADER;
typedef struct WAVEFORMATEX {
uint32_t wFormatTag;
uint32_t nChannels;
uint64_t nSamplesPerSec;
uint64_t nAvgBytesPerSec;
uint32_t nBlockAlign;
uint32_t wBitsPerSample;
uint32_t cbSize;
} WAVEFORMATEX;
#pragma pack ()
typedef struct _listareastruct {
FOURCC fcc; // 标识
uint64_t cb; // 大小,不包括最初的8个字节(fcc和cb两个域)
FOURCC type; // LIST类型
} LISTAREASTRUCT;
typedef struct _ChunkStruct
{
FOURCC fcc; // 标识
uint64_t cb; // 块大小,不包括本结构
} CHUNKSTRUCT;
// prefix AMHF denoting Avi Main Header Flag
#define AMHF_HASINDEX 0x00000010 //是否包含索引
#define AMHF_MUSTUSEINDEX 0x00000020
#define AMHF_ISINTERLEAVED 0x00000100 //是否包含保留区域
#define AMHF_TRUSTCKTYPE 0x00000800 /* Use CKType to find key frames? */
#define AMHF_WASCAPTUREFILE 0x00010000
#define AMHF_COPYRIGHTED 0x00020000
typedef struct _avimainheader {
FOURCC fcc; // 必须为‘avih’
uint64_t cb; // 本数据结构的大小,不包括最初的8个字节(fcc和cb两个域)
uint64_t dwMicroSecPerFrame; // 视频帧间隔时间(以微秒为单位)
uint64_t dwMaxBytesPerSec; // 这个AVI文件的最大数据率
uint64_t dwPaddingGranularity; // 数据填充的粒度
uint64_t dwFlags; // AVI文件的全局标记,比如是否含有索引块等 (0x810 HASINDEX | TRUSTCKTYPE)
uint64_t dwTotalFrames; // 总帧数
uint64_t dwInitialFrames; // 为交互格式指定初始帧数(非交互格式应该指定为0)
uint64_t dwStreams; // 本文件包含的流的个数
uint64_t dwSuggestedBufferSize; // 建议读取本文件的缓存大小(应能容纳最大的块)
uint64_t dwWidth; // 视频图像的宽(以像素为单位)
uint64_t dwHeight; // 视频图像的高(以像素为单位)
uint64_t dwReserved[4]; // 保留
} AVIMAINHEADER;
typedef struct _avistreamheader {
FOURCC fcc; // '必须为‘strh’
uint64_t cb; // 本数据结构的大小,不包括最初的8个字节(fcc和cb两个域)
FOURCC fccType; // 流的类型:‘auds’(音频流)、‘vids’(视频流)、‘mids’(MIDI流)、‘txts’(文字流)
FOURCC fccHandler; // '指定流的处理者,对于音视频来说就是解码器
uint64_t dwFlags; // '标记:是否允许这个流输出?调色板是否变化?
uint32_t wPriority; // '流的优先级(当有多个相同类型的流时优先级最高的为默认流)
uint32_t wLanguage;
uint64_t dwInitialFrames; // 为交互格式指定初始帧数
uint64_t dwScale; // '这个流使用的时间尺度
// uint64_t dwRate; // 4055
float dwRate; // 4055 使用浮点计算播放时间较精确
uint64_t dwStart; // '流的开始时间
uint64_t dwLength; // '流的帧数 (158)
uint64_t dwSuggestedBufferSize; // '读取这个流数据建议使用的缓存大小1536
uint64_t dwQuality; // 流数据的质量指标(0 ~ 10,000)
uint64_t dwSampleSize; // 'Sample的大小
struct {
short int left;
short int top;
short int right;
short int bottom;
} rcFrame; // '指定这个流(视频流或文字流)在视频主窗口中的显示位置'
// 视频主窗口由AVIMAINHEADER结构中的dwWidth和dwHeight决定
} AVISTREAMHEADER;
// prefix AIEF denoting Avi Index Entry Flag
#define AIEF_LIST 0x00000001L // indexed chunk is a list
#define AIEF_KEYFRAME 0x00000010L // indexed chunk is a key frame
#define AIEF_NOTIME 0x00000100L // indexed chunk frame do not consume any time
#define AIEF_COMPUSE 0x0FFF0000L // these bits are used by compressor
#define AIEF_FIXKEYFRAME 0x00001000L // XXX: borrowed from VLC, avoid using
typedef struct _avioldindex {
FOURCC fcc; // 必须为‘idx1’
uint64_t cb; // 本数据结构的大小,不包括最初的8个字节(fcc和cb两个域)
struct _avioldindex_entry {
uint64_t dwChunkId; // 表征本数据块的四字符码
uint64_t dwFlags; // 说明本数据块是不是关键帧、是不是‘rec ’列表等信息
uint64_t dwOffset; // 本数据块在文件中的偏移量
uint64_t dwSize; // 本数据块的大小
} aIndex[1]; // 这是一个数组!为每个媒体数据块都定义一个索引信息
} AVIOLDINDEX;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
//---------------------------------------------------------------------------------------
static int SetFilePointer(FILE *stream,long offset,int *para2,int fromwhere)
{
fseek(stream,offset,fromwhere);
}
static uint8_t ReadFile(FILE *stream,void *buffer,size_t size,uint64_t *lpNumberOfBytesRead,int *lpOverlapped)
{
int Ret = fread(buffer,size,1,stream);
*lpNumberOfBytesRead = Ret * size;
if (*lpNumberOfBytesRead != size) {
return 0;
} else {
return 1;
}
}
//---------------------------------------------------------------------------------------
static void InitAudioMpeg4(struct _CMPEG4Head *This, uint32_t Channels,uint64_t Sample,uint64_t dwBlockSize)
{
// AVI_set_audio(This->avi_lib,Channels, Sample, 16, WAVE_FORMAT_PCM, Sample);
mp4MuxerAudioInit(Channels, Sample, 16);
}
//---------------------------------------------------------------------------------------
static void StartTimer(struct _CMPEG4Head *This)
{
if(This->dwStartTick == 0) {
This->dwStartTick = MyGetTickCount();
// printf("[%s] StartTick :%ld\n",__FUNCTION__,This->dwStartTick);
}
}
//---------------------------------------------------------------------------------------
static void StopTimer(struct _CMPEG4Head *This)
{
if(This->dwEndTick == 0) {
This->dwEndTick = MyGetTickCount();
// printf("[%s] EndTick :%ld\n",__FUNCTION__,This->dwEndTick);
}
}
//---------------------------------------------------------------------------------------
static uint8_t WriteVideo(struct _CMPEG4Head *This, void *pData,uint32_t dwSize)
{
if (dwSize == 0)
return 0;
pthread_mutex_lock(&This->mutex);
mp4MuxerAppendVideo(pData,dwSize);
This->dwFrameCnt++;
pthread_mutex_unlock(&This->mutex);
}
//---------------------------------------------------------------------------------------
static uint8_t WriteAudio(struct _CMPEG4Head *This, void *pData,uint32_t dwSize)
{
if (dwSize == 0)
return 0;
pthread_mutex_lock(&This->mutex);
mp4MuxerAppendAudio(pData,dwSize);
pthread_mutex_unlock(&This->mutex);
}
//---------------------------------------------------------------------------------------
// 获取AVI文件播放总时间
static int GetAviTotalTime(struct _CMPEG4Head *This)
{
int Ret = 0;
int FileOffset;
uint64_t ReadSize;
AVISTREAMHEADER AviStreamHead;
FileOffset = sizeof(LISTAREASTRUCT)*3 + sizeof(AVIMAINHEADER);
SetFilePointer(This->hFile, FileOffset, NULL, 0);
if(ReadFile(This->hFile,&AviStreamHead,sizeof(AVISTREAMHEADER),&ReadSize,NULL)) {
Ret = (AviStreamHead.dwLength/AviStreamHead.dwRate)-1;
// printf("ret:%d,len:%d,rate:%f\n", Ret,AviStreamHead.dwLength,AviStreamHead.dwRate);
}
//printf("Read Avi File Fail!\n");
SetFilePointer(This->hFile,20+2048*2+256+1024+12,NULL,0);
// printf("time :%d\n",Ret);
return Ret;
}
//--------------------------------------------------------------------------------------
// 获取AVI文件帧率
static int GetAviFileFrameRate(struct _CMPEG4Head *This)
{
int Ret = 0;
int FileOffset;
uint64_t ReadSize;
AVISTREAMHEADER AviStreamHead;
FileOffset = sizeof(LISTAREASTRUCT)*3 + sizeof(AVIMAINHEADER);
SetFilePointer(This->hFile, FileOffset, NULL, 0);
if(ReadFile(This->hFile,&AviStreamHead,sizeof(AVISTREAMHEADER),&ReadSize,NULL)) {
Ret = AviStreamHead.dwRate;
}
//printf("Read Avi File Fail!\n");
SetFilePointer(This->hFile,20+2048*2+256+1024+12,NULL,0);
return Ret;
}
//--------------------------------------------------------------------------------------
// 读视频数据或音频数据
// 返回值 1:视频数据 2:音频数据 0:无效
static int ReadAviData(struct _CMPEG4Head *This, void *pData,uint64_t *dwSize,int *InCameraWidth,int *InCameraHeight)
{
int Ret = 0;
unsigned char tmp;
AVIMAINHEADER AviMainHead;
if(This->hFile != NULL)
{
uint64_t ReadSize;
CHUNKSTRUCT Chunk;
*dwSize = 0;
if (This->ReadFirstFrame == 0) {
This->ReadFirstFrame = 1;
SetFilePointer(This->hFile,sizeof(LISTAREASTRUCT) * 2,NULL,0);
ReadFile(This->hFile,&AviMainHead,sizeof(AVIMAINHEADER),&ReadSize,NULL);
if (ReadSize==sizeof(AVIMAINHEADER)) {
*InCameraWidth = AviMainHead.dwWidth;
*InCameraHeight = AviMainHead.dwHeight;
} else {
return Ret;
}
SetFilePointer(This->hFile,20+2048*2+256+1024+12,NULL,0);
}
ReadFile(This->hFile,&Chunk,sizeof(CHUNKSTRUCT),&ReadSize,NULL);
if(ReadSize==sizeof(CHUNKSTRUCT)) {
if(Chunk.fcc == 0x63643030) {// 视频数据
ReadFile(This->hFile,pData,Chunk.cb,&ReadSize,NULL);
if(Chunk.cb == ReadSize) {
*dwSize = ReadSize;
This->dwStreamSize += (*dwSize + sizeof(CHUNKSTRUCT));
if(This->dwFrameCnt==0) {
This->InitAudioFrame = This->dwAudioFrame;
}
This->dwFrameCnt++;
Ret = 1;
if(*dwSize % 2) {//对齐
ReadFile(This->hFile,&tmp,1,&ReadSize,NULL);
This->dwStreamSize += 1;
}
}
} else if(Chunk.fcc == 0x62773130) {// 音频数据
char *p = (char *)pData;
do{
ReadFile(This->hFile,p,Chunk.cb,&ReadSize,NULL);
p += Chunk.cb;
if(This->dwAudioFrame==0) {
This->InitVideoFrame = This->dwFrameCnt;
}
This->dwAudioFrame++; //音频流帧数
if(ReadSize==Chunk.cb) {
*dwSize += ReadSize;
This->dwStreamSize += (Chunk.cb + sizeof(CHUNKSTRUCT));
Ret = 2;
if(Chunk.cb % 2) { //对齐
ReadFile(This->hFile, &tmp, 1, &ReadSize, NULL);
This->dwStreamSize += 1;
}
}
// 重读一下,看是否还有音频数据
memset(&Chunk, 0, sizeof(CHUNKSTRUCT));
ReadFile(This->hFile,&Chunk,sizeof(CHUNKSTRUCT),&ReadSize,NULL);
if(Chunk.fcc != 0x62773130) {
SetFilePointer(This->hFile,0-sizeof(CHUNKSTRUCT),NULL,SEEK_CUR);
break;
}
}while(1);
}
}
}
return Ret;
}
//---------------------------------------------------------------
static void DestoryMPEG4Head(struct _CMPEG4Head **This)
{
pthread_mutex_lock(&(*This)->mutex);
mp4MuxerStop();
pthread_mutex_unlock(&(*This)->mutex);
if (*This)
free(*This);
(*This) = NULL;
}
//---------------------------------------------------------------
//bReadWrite 读写标志, =0写文件 =1读文件
MPEG4Head* Mpeg4_Create(int Width,int Height,char *FileName, int ReadWrite)
{
struct _CMPEG4Head *This = (MPEG4Head*)calloc(1,sizeof(MPEG4Head));
if(ReadWrite == READ_ONLY) {
} else {
mp4MuxerInit(Width,Height,FileName);
// This->avi_lib = AVI_open_output_file(FileName);
This->dwStartTick = 0;
This->dwEndTick = 0;
This->dwFrameCnt = 0;
This->m_Width = Width;
This->m_Height = Height;
This->FirstFrame = 1;
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&This->mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
}
This->InitAudio = InitAudioMpeg4;
This->WriteVideo = WriteVideo;
This->WriteAudio = WriteAudio;
This->GetAviTotalTime = GetAviTotalTime;
This->GetAviFileFrameRate = GetAviFileFrameRate;
This->ReadAviData = ReadAviData;
This->DestoryMPEG4 = DestoryMPEG4Head;
return This;
}
<file_sep>/src/app/rdface/rd_face.h
/*
* =============================================================================
*
* Filename: rd_face.h
*
* Description: 阅面人脸识别算法接口
*
* Version: 1.0
* Created: 2019-06-17 17:13:03
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _RD_FACE_H
#define _RD_FACE_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define SIMILAYRITY 0.4
int rdfaceInit(void);
void rdfaceUninit(void);
float rdfaceGetFeatureSimilarity(float *feature1, float *feature2);
int rdfaceRegist(unsigned char *image_buff,int w,int h,float **out_feature,int *out_feature_size);
int rdfaceRecognizer(unsigned char *image_buff,int w,int h,
int (*featureCompare)(float *feature,void *face_data_out,int gender,int age),void *face_data_out);
int rdfaceRecognizerOnce(unsigned char *image_buff,int w,int h,int *age,int *sex);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/hal/hal_sensor.c
/*
* =============================================================================
*
* Filename: hal_sensor.c
*
* Description: 室内接近传感器
*
* Version: 1.0
* Created: 2019-07-06 15:30:59
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <linux/input.h>
#include <fcntl.h>
#include <unistd.h>
#include "hal_sensor.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static int sensor_fd = -1;
void halSensorInit(void)
{
sensor_fd = open ("/dev/input/event2", O_RDONLY);
if(sensor_fd <= 0) {
printf("open /dev/input/event2 device error!\n");
return ;
}
}
int halSensorGetState(void)
{
if (sensor_fd < 0) {
return HAL_SENSER_ERR;
}
struct input_event s_event;
if(read (sensor_fd, &s_event, sizeof(struct input_event)) == sizeof(struct input_event) <= 0)
return HAL_SENSER_ERR;
if(s_event.type != EV_ABS)
return HAL_SENSER_ERR;
if(s_event.code != ABS_DISTANCE)
return HAL_SENSER_ERR;
if(s_event.value == 0)
return HAL_SENSOR_INACTIVE;
else if(s_event.value == 1)
return HAL_SENSOR_ACTIVE;
return HAL_SENSER_ERR;
}
void halSensorUninit(void)
{
if (sensor_fd > 0)
close(sensor_fd);
}
<file_sep>/CMakeLists.txt
# CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8)
# 项目名称
project (cmake_project_mode)
# 项目版本
set (VERSION_MAJOR 1)
set (VERSION_MINOR 0)
configure_file (
"${PROJECT_SOURCE_DIR}/include/cmake_config.h.in"
"${PROJECT_SOURCE_DIR}/include/cmake_config.h"
)
# 设置默认编译平台
option(PLATFORM_RV1108 "This is a option for rv1108" ON)
# 设置编译功能
option(MODE_UCPAAS "This is a option for ucpass" ON)
option(MODE_FACE "This is a option for face" ON)
option(MODE_UART "This is a option for uart" ON)
option(MODE_VIDEO "This is a option for video" ON)
option(MODE_UDPTALK "This is a option for udptalk" ON)
option(AUTO_SLEEP "This is a option for auto_sleep" ON)
# 添加编译过程变量
# set(CMAKE_VERBOSE_MAKEFILE ON)
# 设置交叉编译环境 ------------
set(CMAKE_SYSTEM_NAME Linux)
if (PLATFORM_RV1108)
set(TOOLCHAIN_DIR $ENV{RV1108_CROOS_PATH})
set(TOOLCHAIN ${TOOLCHAIN_DIR}/bin/arm-linux-)
endif()
set(CMAKE_C_COMPILER ${TOOLCHAIN}gcc)
set(CMAKE_CXX_COMPILER ${TOOLCHAIN}g++)
set(CMAKE_AR ${TOOLCHAIN}ar)
set(CMAKE_LINKER ${TOOLCHAIN}ld)
set(CMAKE_NM ${TOOLCHAIN}nm)
set(CMAKE_OBJDUMP ${TOOLCHAIN}objdump)
set(CMAKE_RANLIB ${TOOLCHAIN}ranlib)
set(CMAKE_STRIP ${TOOLCHAIN}strip)
if (PLATFORM_RV1108)
set(CMAKE_C_FLAGS "-DRV1108 ${CMAKE_C_FLAGS}")
set(CMAKE_CXX_FLAGS "-DRV1108 ${CMAKE_CXX_FLAGS}")
else()
set(CMAKE_C_FLAGS "-DX86 ${CMAKE_C_FLAGS}")
set(CMAKE_CXX_FLAGS "-DX86 ${CMAKE_CXX_FLAGS}")
endif()
# 设置debug编译和release编译配置
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -O0 -DWATCHDOG_DEBUG")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -DWATCHDOG_DEBUG")
set(CMAKE_C_FLAGS_RELEASE "-O2")
set(CMAKE_CXX_FLAGS_RELEASE "-O2")
# 设置交叉编译环境 ------------
#设置执行文件存放路径
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR})
#设置库文件存放路径
#set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/libs)
#功能函数获取当前目录及子目录(递归获取),添加到头文件搜索路径
function(func_include_sub_directories_recursively root_dir)
if (IS_DIRECTORY ${root_dir}) # 当前路径如果是一个目录,则加入到包含目录
include_directories(${root_dir})
endif()
file(GLOB ALL_SUB RELATIVE ${root_dir} ${root_dir}/*) # 获得当前目录下的所有文件,加如ALL_SUB列表中
foreach(sub ${ALL_SUB})
if (IS_DIRECTORY ${root_dir}/${sub})
func_include_sub_directories_recursively(${root_dir}/${sub}) # 对子目录递归调用,包含
endif()
endforeach()
endfunction()
# 项目的所有目录都为头文件搜索路径
func_include_sub_directories_recursively(${PROJECT_SOURCE_DIR}/src)
func_include_sub_directories_recursively(${PROJECT_SOURCE_DIR}/module)
# 增加其他目录头文件路径
include_directories(
${PROJECT_SOURCE_DIR}/include
${PROJECT_SOURCE_DIR}/include/mqtt
${PROJECT_SOURCE_DIR}/include/ffmpeg
)
if (PLATFORM_RV1108)
include_directories(
${PROJECT_SOURCE_DIR}/include/sdk_include
)
endif()
# 添加库文件搜索路径
if (PLATFORM_RV1108)
link_directories(
${PROJECT_SOURCE_DIR}/lib/arm
${PROJECT_SOURCE_DIR}/lib/arm/sdk_system_lib
${PROJECT_SOURCE_DIR}/lib/arm/sdk_rootfs_lib
${PROJECT_SOURCE_DIR}/lib/arm/sdk_ucpaas_lib
${PROJECT_SOURCE_DIR}/lib/arm/ffmpeg_lib
)
else()
link_directories(
${PROJECT_SOURCE_DIR}/lib/x86
/usr/local/lib
/usr/lib/x86_64-linux-gnu
/usr/lib
)
endif()
# 添加库文件名称
link_libraries (
pthread asound
)
if (MODE_UCPAAS)
add_definitions(-DUSE_UCPAAS)
endif()
if (MODE_FACE)
add_definitions(-DUSE_FACE)
endif()
if (MODE_UART)
add_definitions(-DUSE_UART)
endif()
if (MODE_VIDEO)
add_definitions(-DUSE_VIDEO)
endif()
if (MODE_UDPTALK)
add_definitions(-DUSE_UDPTALK)
endif()
if (AUTO_SLEEP)
add_definitions(-DAUTO_SLEEP)
endif()
# 添加宏定义
# include(define.cmake)
# 增加打印信息
# message(STATUS "message test ${PROJECT_SOURCE_DIR}")
# 指定应用名称
set(EXE cat_eye)
# 增加子目录,可以传递参数
add_subdirectory(src)
if (PLATFORM_RV1108)
add_subdirectory(module)
endif()
<file_sep>/include/mpi/mpp_time.h
/*
* Copyright 2015 Rockchip Electronics Co. LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __MPP_TIME_H__
#define __MPP_TIME_H__
#include "mpp_sdk_interface.h"
// TODO: add usleep function on windows
#if defined(_WIN32) && !defined(__MINGW32CE__)
#include <windows.h>
#define msleep Sleep
#define sleep(x) Sleep((x)*1000)
#else
#include <unistd.h>
#define msleep(x) usleep((x)*1000)
#endif
typedef void* MppTimer;
#ifdef __cplusplus
extern "C" {
#endif
RK_S64 mpp_time();
void mpp_time_diff(RK_S64 start, RK_S64 end, RK_S64 limit, const char *fmt);
/*
* Timer create / destroy / enable / disable function
* Note when timer is create it is default disabled user need to call enable
* fucntion with enable = 1 to enable the timer.
* User can use enable function with enable = 0 to disable the timer.
*/
MppTimer mpp_timer_get(const char *name);
void mpp_timer_put(MppTimer timer);
void mpp_timer_enable(MppTimer timer, RK_U32 enable);
/*
* Timer basic operation function:
* start : let timer start timing counter
* pause : let timer pause and return the diff to start time
* reset : let timer counter to all zero
*/
RK_S64 mpp_timer_start(MppTimer timer);
RK_S64 mpp_timer_pause(MppTimer timer);
RK_S64 mpp_timer_reset(MppTimer timer);
/*
* These timer helper function can only be call when timer is paused:
* mpp_timer_get_sum - Return timer sum up total value
* mpp_timer_get_count - Return timer sum up counter value
* mpp_timer_get_name - Return timer name
*/
RK_S64 mpp_timer_get_sum(MppTimer timer);
RK_S64 mpp_timer_get_count(MppTimer timer);
const char *mpp_timer_get_name(MppTimer timer);
#ifdef __cplusplus
}
#endif
#endif /*__MPP_TIME_H__*/
<file_sep>/module/cap/buffer/md_camerabuf.cpp
#include "md_camerabuf.h"
RKCameraBuffer::RKCameraBuffer(ion_user_handle_t handle, int sharefd,
unsigned long phy, void* vaddr, const char* camPixFmt,
unsigned int width, unsigned int height, int stride,size_t size,
weak_ptr<CameraBufferAllocator> allocator,
weak_ptr<ICameraBufferOwener> bufOwener)
: CameraBuffer(allocator, bufOwener), mHandle(handle), mShareFd(sharefd),
mPhy(phy), mVaddr(vaddr), mWidth(width), mHeight(height), mBufferSize(size),
mCamPixFmt(camPixFmt), mStride(stride) {
}
RKCameraBuffer::~RKCameraBuffer(void) {
if (!mAllocator.expired()) {
shared_ptr<CameraBufferAllocator> spAlloc = mAllocator.lock();
if (spAlloc.get()) {
cout<<"line "<<__LINE__<<" func:"<<__func__<<"\n";
spAlloc->free(this);
}
}
}
void* RKCameraBuffer::getHandle(void) const {
return (void*)&mHandle;
}
void* RKCameraBuffer::getPhyAddr(void) const {
return (void*)mPhy;
}
void* RKCameraBuffer::getVirtAddr(void) const {
return mVaddr;
}
const char* RKCameraBuffer::getFormat(void) {
return mCamPixFmt;
}
unsigned int RKCameraBuffer::getWidth(void) {
return mWidth;
}
unsigned int RKCameraBuffer::getHeight(void) {
return mHeight;
}
size_t RKCameraBuffer::getDataSize(void) const {
return mDataSize;
}
void RKCameraBuffer::setDataSize(size_t size) {
mDataSize = size;
}
size_t RKCameraBuffer::getCapacity(void) const {
return mBufferSize;
}
unsigned int RKCameraBuffer::getStride(void) const {
return mStride;
}
bool RKCameraBuffer::lock(unsigned int usage) {
UNUSED_PARAM(usage);
return true;
}
bool RKCameraBuffer::unlock(unsigned int usage) {
UNUSED_PARAM(usage);
return true;
}
RKCameraBufferAllocator::RKCameraBufferAllocator(void) {
mIonClient = ion_open();
if (mIonClient < 0) {
printf("open /dev/ion failed!\n");
mError = true;
}
}
RKCameraBufferAllocator::~RKCameraBufferAllocator(void) {
ion_close(mIonClient);
if (mNumBuffersAllocated > 0) {
printf("%s: memory leak; %d camera buffers have not been freed", __func__, mNumBuffersAllocated);
}
}
std::shared_ptr<CameraBuffer>
RKCameraBufferAllocator::alloc(const char* camPixFmt, unsigned int width, unsigned int height,
unsigned int usage, weak_ptr<ICameraBufferOwener> bufOwener)
{
int ret;
ion_user_handle_t buffHandle;
int stride;
int sharefd;
void* vaddr;
size_t buffer_size;
shared_ptr<RKCameraBuffer> camBuff;
unsigned int ionFlags = 0;
unsigned int halPixFmt;
unsigned long phy = 0;
int type = ION_HEAP_TYPE_DMA_MASK;
if (usage & CameraBuffer::WRITE)
ionFlags |= PROT_WRITE;
if (usage & CameraBuffer::READ)
ionFlags |= PROT_READ;
buffer_size = calcBufferSize(camPixFmt, (width + 0xf) & ~0xf, (height + 0xf) & ~0xf);
stride = width;
ret = ion_alloc(mIonClient, buffer_size, 0, type, 0, &buffHandle);
ret = ion_share(mIonClient, buffHandle, &sharefd);
if (ret != 0) {
printf("%s: ion buffer allocation failed (error %d)", __func__, ret);
goto alloc_end;
}
if (type == ION_HEAP_TYPE_DMA_MASK)
ion_get_phys(mIonClient, buffHandle, &phy);
vaddr = mmap(NULL, buffer_size, ionFlags, MAP_SHARED, sharefd, 0);
camBuff = shared_ptr<RKCameraBuffer> (new RKCameraBuffer(buffHandle, sharefd, phy, vaddr, camPixFmt, width, height, stride,
buffer_size, shared_from_this(), bufOwener));
if (!camBuff.get()) {
printf("%s: Out of memory", __func__);
} else {
mNumBuffersAllocated++;
if (camBuff->error()) {
}
}
alloc_end:
return camBuff;
}
void RKCameraBufferAllocator::free(CameraBuffer* buffer) {
int ret;
if (buffer) {
RKCameraBuffer* camBuff = static_cast<RKCameraBuffer*>(buffer);
if (camBuff->mVaddr)
munmap(camBuff->mVaddr, camBuff->mBufferSize);
if (camBuff->mShareFd)
close(camBuff->mShareFd);
camBuff->mShareFd = -1;
ret = ion_free(mIonClient, camBuff->mHandle);
if (ret != 0) {
printf("%s: ion free buffer failed (error %d)", __func__, ret);
}
mNumBuffersAllocated--;
}
}
<file_sep>/src/app/my_echo.h
/*
* =============================================================================
*
* Filename: my_echo.h
*
* Description: 消回音处理
*
* Version: 1.0
* Created: 2019-08-05 10:33:29
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_ECHO_H
#define _MY_ECHO_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
void rkEchoTx(short int *pshwIn,
short int *pshwRef,
short int *pshwOut,
int swFrmLen);
void rkEchoRx(short int *pshwIn,
short int *pshwOut,
int swFrmLen);
void rkEchoInit(void);
void rkEchoUnInit(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/video/video_server.h
#ifndef _VIDEO_SERVICE_H
#define _VIDEO_SERVICE_H
typedef void (*EncCallbackFunc)(void *data,int size,int frame_type);
typedef void (*RecordStopCallbackFunc)(void);
int rkVideoInit(void);
int rkVideoDisplayLocal(void);
int rkVideoDisplayPeer(int w,int h,void* encCallback);
int rkVideoDisplayOff(void);
int rkVideoFaceOnOff(int type);
int rkVideoStop(void);
int rkH264EncOn(int w,int h,EncCallbackFunc encCallback);
int rkH264EncOff(void);
int rkVideoCapture(char *file_name);
int rkVideoRecordStart(int w,int h,EncCallbackFunc encCallback);
int rkVideoRecordSetStopFunc(RecordStopCallbackFunc recordCallback);
int rkVideoRecordStop(void);
int rkGetVideoRun(void);
#endif
<file_sep>/src/gui/my_controls/CMakeLists.txt
# 查找当前目录下的所有源文件
# 并将名称保存到 MY_CONTROLS_SRCS 变量
aux_source_directory(. MY_CONTROLS_SRCS)
STRING( REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER ${CMAKE_CURRENT_SOURCE_DIR})
# message(STATUS "message mode ${CURRENT_FOLDER}")
# 将当前目录作为库文件名添加到全局变量ADD_LIBS中,需要加PARENT_SCOPE生效父接文件变量
# set (ADD_LIBS ${CURRENT_FOLDER} ${ADD_LIBS} PARENT_SCOPE)
# message(STATUS "message mode1 ${ADD_LIBS}")
# 生成链接库
add_library (${CURRENT_FOLDER} ${MY_CONTROLS_SRCS})
<file_sep>/module/video/main.cpp
#include <list>
#include "md_camerahal.h"
#include "md_camerabuf.h"
#include "thread_helper.h"
#include "process/md_display_process.h"
#include "process/md_encoder_process.h"
#include "protocol.h"
#include "config.h"
#include "ipc_server.h"
#include "queue.h"
#define COLOR_KEY_R 0x0
#define COLOR_KEY_G 0x0
#define COLOR_KEY_B 0x1
static IpcServer* ipc_video = NULL;
static Queue *main_queue = NULL;
class RKVideo {
public:
RKVideo();
~RKVideo();
int connect(std::shared_ptr<CamHwItf::PathBase> mpath,
std::shared_ptr<StreamPUBase> next,
frm_info_t& frmFmt, const uint32_t num,
std::shared_ptr<RKCameraBufferAllocator> allocator);
void disconnect(std::shared_ptr<CamHwItf::PathBase> mpath,
std::shared_ptr<StreamPUBase> next);
void displayLocal(void);
void h264EncOnOff(bool type,int w,int h,EncCallbackFunc encCallback);
void capture(char *file_name);
void recordStart(EncCallbackFunc recordCallback);
void recordSetStopFunc(RecordStopCallbackFunc recordCallback);
void recordStop(void);
private:
int display_state_; // 0关闭 1本地视频 2远程视频
bool h264enc_state_;
struct rk_cams_dev_info cam_info;
std::shared_ptr<RKCameraBufferAllocator> ptr_allocator;
CameraFactory cam_factory;
std::shared_ptr<RKCameraHal> cam_dev;
std::shared_ptr<DisplayProcess> display_process;
std::shared_ptr<H264Encoder> encode_process;
};
static RKVideo* rkvideo = NULL;
static int init_ok = 0;
RKVideo::RKVideo()
{
display_state_ = false;
h264enc_state_ = false;
memset(&cam_info, 0, sizeof(cam_info));
CamHwItf::getCameraInfos(&cam_info);
if (cam_info.num_camers <= 0) {
printf("[rv_video:%s]fail\n",__func__);
return ;
}
shared_ptr<CamHwItf> new_dev = cam_factory.GetCamHwItf(&cam_info, 0);
cam_dev = ((shared_ptr<RKCameraHal>)
new RKCameraHal(new_dev, cam_info.cam[0]->index, cam_info.cam[0]->type));
cam_dev->init(1280, 720, 25);
ptr_allocator = shared_ptr<RKCameraBufferAllocator>(new RKCameraBufferAllocator());
cam_dev->start(4, ptr_allocator);
display_process = std::make_shared<DisplayProcess>();
if (display_process.get() == nullptr)
std::cout << "[rv_video]DisplayProcess make_shared error" << std::endl;
encode_process = std::make_shared<H264Encoder>();
if (encode_process.get() == nullptr)
std::cout << "[rv_video]H264Encoder make_shared error" << std::endl;
init_ok = 1;
}
RKVideo::~RKVideo()
{
disconnect(cam_dev->mpath(), display_process);
if (cam_dev)
cam_dev->stop();
init_ok = 0;
}
int RKVideo::connect(std::shared_ptr<CamHwItf::PathBase> mpath,
std::shared_ptr<StreamPUBase> next,
frm_info_t& frmFmt, const uint32_t num,
std::shared_ptr<RKCameraBufferAllocator> allocator)
{
if (!mpath.get() || !next.get()) {
printf("[rv_video:%s]PathBase,PU is NULL\n",__func__);
}
mpath->addBufferNotifier(next.get());
next->prepare(frmFmt, num, allocator);
if (!next->start()) {
printf("[rv_video:%s]PathBase,PU start failed!\n",__func__);
}
return 0;
}
void RKVideo::disconnect(std::shared_ptr<CamHwItf::PathBase> mpath,
std::shared_ptr<StreamPUBase> next)
{
if (!mpath.get() || !next.get()) {
printf("[rv_video:%s]PathBase,PU is NULL\n",__func__);
return;
}
mpath->removeBufferNotifer(next.get());
next->stop();
next->releaseBuffers();
}
void RKVideo::displayLocal(void)
{
if (cam_info.num_camers <= 0)
return;
if (display_state_ != 1) {
display_state_ = 1;
connect(cam_dev->mpath(), display_process, cam_dev->format(), 0, nullptr);
}
}
void RKVideo::h264EncOnOff(bool type,int w,int h,EncCallbackFunc encCallback)
{
if (cam_info.num_camers <= 0)
return;
if (type == true) {
if (h264enc_state_ == false) {
h264enc_state_ = true;
connect(cam_dev->mpath(), encode_process, cam_dev->format(), 1, ptr_allocator);
encode_process->startEnc(w,h,encCallback);
}
} else {
if (h264enc_state_ == true) {
h264enc_state_ = false;
encode_process->stopEnc();
disconnect(cam_dev->mpath(), encode_process);
}
}
}
void RKVideo::capture(char *file_name)
{
if (display_state_ == 0)
return;
display_process->capture(file_name);
}
void RKVideo::recordStart(EncCallbackFunc recordCallback)
{
if (display_state_ != 1)
return ;
h264EncOnOff(true,320,240,NULL);
encode_process->recordStart(recordCallback);
}
void RKVideo::recordSetStopFunc(RecordStopCallbackFunc recordStopCallback)
{
encode_process->recordSetStopFunc(recordStopCallback);
}
void RKVideo::recordStop(void)
{
encode_process->recordStop();
h264EncOnOff(false,0,0,NULL);
}
static int rkH264EncOn(int w,int h,EncCallbackFunc encCallback)
{
if (rkvideo)
rkvideo->h264EncOnOff(true,w,h,encCallback);
}
static int rkH264EncOff(void)
{
if (rkvideo)
rkvideo->h264EncOnOff(false,0,0,NULL);
}
static int rkVideoCapture(char *file_name)
{
if (rkvideo)
rkvideo->capture(file_name);
}
static int rkVideoRecordStart(EncCallbackFunc recordCallback)
{
if (rkvideo)
rkvideo->recordStart(recordCallback);
}
static int rkVideoRecordSetStopFunc(RecordStopCallbackFunc recordCallback)
{
if (rkvideo)
rkvideo->recordSetStopFunc(recordCallback);
}
static int rkVideoRecordStop(void)
{
if (rkvideo)
rkvideo->recordStop();
}
static void display_clean_uiwin(void)
{
struct win * ui_win;
struct color_key color_key;
unsigned short rgb565_data;
unsigned short *ui_buff;
int i;
int w, h;
ui_win = rk_fb_getuiwin();
ui_buff = (unsigned short *)ui_win->buffer;
/* enable and set color key */
color_key.enable = 1;
color_key.red = (COLOR_KEY_R & 0x1f) << 3;
color_key.green = (COLOR_KEY_G & 0x3f) << 2;
color_key.blue = (COLOR_KEY_B & 0x1f) << 3;
rk_fb_set_color_key(color_key);
rk_fb_get_out_device(&w, &h);
/* set ui win color key */
rgb565_data = (COLOR_KEY_R & 0x1f) << 11 | ((COLOR_KEY_G & 0x3f) << 5) | (COLOR_KEY_B & 0x1f);
for (i = 0; i < w * h; i ++) {
ui_buff[i] = rgb565_data;
}
}
static void callbackEncode(void *data,int size,int fram_type)
{
}
static void callbackCapture(void)
{
IpcData ipc_cap;
ipc_cap.cmd = IPC_VIDEO_CAPTURE_END;
main_queue->post(main_queue,&ipc_cap);
}
static void callbackIpc(char *data,int size )
{
IpcData ipc_data;
memcpy(&ipc_data,data,sizeof(IpcData));
switch(ipc_data.cmd)
{
case IPC_VIDEO_ENCODE_ON:
rkH264EncOn(320,240,callbackEncode);
break;
case IPC_VIDEO_ENCODE_OFF:
rkH264EncOff();
break;
case IPC_UART_CAPTURE:
for (int i = 0; i < ipc_data.count; ++i) {
char path[128];
sprintf(path,"%s%s_%d.jpg",FAST_PIC_PATH,ipc_data.data.file.path,i);
rkVideoCapture(path);
usleep(500000);
}
break;
case IPC_VIDEO_RECORD_START:
break;
case IPC_VIDEO_RECORD_STOP:
break;
default:
break;
}
}
static void* threadIpcSendMain(void *arg)
{
Queue * queue = (Queue *)arg;
waitIpcOpen(IPC_MAIN);
IpcData ipc_data;
while (1) {
queue->get(queue,&ipc_data);
ipc_data.dev_type = IPC_DEV_TYPE_VIDEO;
if (ipc_video)
ipc_video->sendData(ipc_video,IPC_MAIN,&ipc_data,sizeof(IpcData));
}
return NULL;
}
int main(int argc, char *argv[])
{
rk_fb_init(FB_FORMAT_BGRA_8888);
rk_fb_set_yuv_range(CSC_BT601F);
display_clean_uiwin();
rkvideo = new RKVideo();
if (rkvideo)
rkvideo->displayLocal();
main_queue = queueCreate("main_queue",QUEUE_BLOCK,sizeof(IpcData));
createThread(threadIpcSendMain,main_queue);
ipc_video = ipcCreate(IPC_CAMMER,callbackIpc);
while (access(IPC_MAIN,0) != 0) {
usleep(10000);
}
delete rkvideo;
remove(IPC_CAMMER);
return 0;
}
<file_sep>/src/hal/hal_battery.h
/*
* =============================================================================
*
* Filename: hal_battery.h
*
* Description: 硬件层 看门狗接口
*
* Version: virsion
* Created: 2018-12-12 15:52:30
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _HAL_BATTERY_H
#define _HAL_BATTERY_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
enum {
BATTERY_NORMAL,
BATTERY_CHARGING,
};
int halBatteryGetEle(void);
int halBatteryGetState(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/drivers/qrenc.h
/*
* =============================================================================
*
* Filename: qrenc.h
*
* Description: 生成二维码PNG图片
*
* Version: 1.0
* Created: 2019-05-25 14:52:46
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _QRENC_H
#define _QRENC_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* ---------------------------------------------------------------------------*/
/**
* @brief qrcodeString 调用接口生成二维码
*
* @param string 二维码字符串内容
* @param path 保存图片路径,包含扩展名,例如xx/xx.png
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
int qrcodeString(unsigned char *string,char *path);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/gui/form_main.c
/*
* =============================================================================
*
* Filename: FormMain.c
*
* Description: 主窗口
*
* Version: 1.0
* Created: 2016-02-23 15:32:24
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <time.h>
#include <string.h>
#include "externfunc.h"
#include "debug.h"
#include "screen.h"
#include "config.h"
#include "thread_helper.h"
#include "sensor_detector.h"
#include "my_button.h"
#include "my_status.h"
#include "my_static.h"
#include "my_battery.h"
#include "my_video.h"
#include "form_video.h"
#include "form_base.h"
#include "protocol.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
extern int createFormSetting(HWND hMainWnd,void (*callback)(void));
extern int createFormVideo(HWND hVideoWnd,int type,void (*callback)(void),int count);
extern int createFormMonitor(HWND hMainWnd,void (*callback)(void));
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formMainProc(HWND hWnd, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void buttonRecordPress(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonCapturePress(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonVideoPress(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonAccessPress(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonSettingPress(HWND hwnd, int id, int nc, DWORD add_data);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_MAIN > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
enum {
MSG_MAIN_TIMER_START = MSG_USER + 1,
MSG_MAIN_TIMER_STOP,
MSG_MAIN_SHOW_NORMAL,
MSG_MAIN_LOAD_BMP,
};
typedef void (*InitBmpFunc)(void) ;
#define BMP_LOCAL_PATH "main/"
#define TIME_1S (10 * 5)
#define TIME_100MS (TIME_1S / 10)
enum {
IDC_TIMER_1S = IDC_FORM_MAIN_START,
IDC_MYSTATUS_WIFI ,
IDC_MYSTATUS_SDCARD,
IDC_MYBATTERY,
IDC_MYSTATIC_DATE,
IDC_MYSTATIC_BATTERY,
IDC_BUTTON_RECORD,
IDC_BUTTON_CAPTURE,
IDC_BUTTON_VIDEO,
IDC_BUTTON_ACCESS,
IDC_BUTTON_SETTING,
IDC_STATE_COM,
};
typedef struct _FormMainTimers {
void (*proc)(HWND hWnd);
int time;
}FormMainTimers;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
PLOGFONT font22;
PLOGFONT font20;
static BmpLocation base_bmps[] = {
{NULL},
};
static MyCtrlStatus ctrls_status[] = {
{IDC_MYSTATUS_WIFI, "wifi",16,10,5},
{IDC_MYSTATUS_SDCARD, "sdcard",54,8,1},
// {IDC_MYSTATUS_BATTERY,"Battery",963,10,3},
{0},
};
static MyCtrlStatic ctrls_static[] = {
{IDC_MYSTATIC_DATE, MYSTATIC_TYPE_TEXT,0,0,1024,40,"",0xffffff,0x00000060},
{0},
};
static MyCtrlButton ctrls_button[] = {
#if 0
{IDC_BUTTON_RECORD, MYBUTTON_TYPE_TWO_STATE,"记录",80,451,buttonRecordPress},
{IDC_BUTTON_CAPTURE,MYBUTTON_TYPE_TWO_STATE,"抓拍",273,451,buttonCapturePress},
{IDC_BUTTON_ACCESS, MYBUTTON_TYPE_TWO_STATE,"门禁",467,451,buttonAccessPress},
{IDC_BUTTON_VIDEO, MYBUTTON_TYPE_TWO_STATE,"录像",662,451,buttonVideoPress},
{IDC_BUTTON_SETTING,MYBUTTON_TYPE_TWO_STATE,"设置",855,451,buttonSettingPress},
#else
{IDC_BUTTON_CAPTURE,MYBUTTON_TYPE_TWO_STATE,"抓拍",80,451,buttonCapturePress},
{IDC_BUTTON_ACCESS, MYBUTTON_TYPE_TWO_STATE,"门禁",338,451,buttonAccessPress},
{IDC_BUTTON_VIDEO, MYBUTTON_TYPE_TWO_STATE,"录像",596,451,buttonVideoPress},
{IDC_BUTTON_SETTING,MYBUTTON_TYPE_TWO_STATE,"设置",855,451,buttonSettingPress},
#endif
{0},
};
static MyCtrlBattery ctrls_battery[] = {
{IDC_MYBATTERY, 910,0,110,40},
{0},
};
static MY_CTRLDATA ChildCtrls [] = {
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
WS_EX_NONE ,//| WS_EX_AUTOSECONDARYDC,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "Fmain",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formMainProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
};
static int bmp_load_finished = 0;
static int flag_timer_stop = 0;
static FormBase* form_base = NULL;
/* ---------------------------------------------------------------------------*/
/**
* @brief formMainTimerStart 开启定时器 单位100ms
*
* @param idc_timer 定时器id号,同时也是编号
*/
/* ---------------------------------------------------------------------------*/
static void formMainTimerStart(int idc_timer)
{
SendMessage(form_base->hDlg, MSG_MAIN_TIMER_START, (WPARAM)idc_timer, 0);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formMainTimerStop 关闭定时器
*
* @param idc_timer 定时器id号
*/
/* ---------------------------------------------------------------------------*/
static void formMainTimerStop(int idc_timer)
{
SendMessage(form_base->hDlg, MSG_MAIN_TIMER_STOP, (WPARAM)idc_timer, 0);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formMainTimerGetState 返回定时器当前是否激活
*
* @param idc_timer
*
* @returns 1激活 0未激活
*/
/* ---------------------------------------------------------------------------*/
static int formMainTimerGetState(int idc_timer)
{
return IsTimerInstalled(form_base->hDlg,idc_timer);
}
static void enableAutoClose(void)
{
Screen.setCurrent(form_base_priv.name);
flag_timer_stop = 0;
my_video->showLocalVideo();
my_video->recordStop();
}
/* ---------------------------------------------------------------------------*/
/**
* @brief updateTime 更新显示时间
*/
/* ---------------------------------------------------------------------------*/
static void updateTime(void)
{
// 更新时间
static struct tm tm_old;
char buf[16] = {0};
struct tm *tm = getTime();
if ((tm_old.tm_hour != tm->tm_hour) || (tm_old.tm_min != tm->tm_min)) {
memcpy(&tm_old,tm,sizeof(struct tm));
sprintf(buf,"%d:%02d",tm->tm_hour,tm->tm_min);
SendMessage(GetDlgItem (form_base->hDlg, IDC_MYSTATIC_DATE),
MSG_MYSTATIC_SET_TITLE,(WPARAM)buf,0);
}
}
static void updateSdcard(void)
{
// 更新SD卡状态
static int sdcartd_state_old = -1;
int sdcartd_state = checkSD();
if (sdcartd_state != sdcartd_state_old) {
sdcartd_state_old = sdcartd_state;
if (sdcartd_state != -1) {
createSdcardDirs();
ShowWindow(GetDlgItem (form_base->hDlg, IDC_MYSTATUS_SDCARD),SW_HIDE);
} else
ShowWindow(GetDlgItem (form_base->hDlg, IDC_MYSTATUS_SDCARD),SW_SHOWNORMAL);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief updateNetwork 更新网络图标
*/
/* ---------------------------------------------------------------------------*/
static void updateNetwork(void)
{
// 更新网络状态
static int net_level_old = 0;
int net_level = 0;
if (g_config.net_config.enable) {
if (getWifiConfig(&net_level) != 0)
net_level = 0;
} else
net_level = 0;
if (net_level > 4)
net_level = 4;
if (net_level != net_level_old) {
net_level_old = net_level;
SendMessage(GetDlgItem (form_base->hDlg, IDC_MYSTATUS_WIFI),
MSG_MYSTATUS_SET_LEVEL,net_level,0);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formMainTimerProc1s 窗口相关定时函数
*
* @returns 1按键超时退出 0未超时退出
*/
/* ---------------------------------------------------------------------------*/
static void formMainTimerProc1s(HWND hwnd)
{
updateNetwork();
updateTime();
updateSdcard();
}
static void buttonRecordPress(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
flag_timer_stop = 1;
}
static void buttonCapturePress(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
flag_timer_stop = 1;
my_video->capture(CAP_TYPE_FORMMAIN,1,NULL,NULL);
}
static void buttonAccessPress(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
flag_timer_stop = 1;
createFormMonitor(GetParent(hwnd),enableAutoClose);
}
static void buttonVideoPress(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
flag_timer_stop = 1;
if (my_video->recordStart(CAP_TYPE_FORMMAIN))
createFormVideo(GetParent(hwnd),FORM_VIDEO_TYPE_RECORD,enableAutoClose,0);
}
static void buttonSettingPress(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
flag_timer_stop = 1;
createFormSetting(GetParent(hwnd),enableAutoClose);
my_video->hideVideo();
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formMainLoadBmp 加载主界面图片
*/
/* ---------------------------------------------------------------------------*/
void formMainLoadBmp(void)
{
if (bmp_load_finished == 1)
return;
printf("[%s]\n", __FUNCTION__);
bmpsLoad(base_bmps);
my_button->bmpsLoad(ctrls_button,BMP_LOCAL_PATH);
my_status->bmpsLoad(ctrls_status,BMP_LOCAL_PATH);
bmp_load_finished = 1;
}
static void formMainReleaseBmp(void)
{
printf("[%s]\n", __FUNCTION__);
bmpsRelease(base_bmps);
}
static void interfaceUpdateElePower(int power)
{
SendMessage(GetDlgItem (form_base->hDlg, IDC_MYBATTERY),
MSG_SET_QUANTITY,(WPARAM)power,0);
}
static void interfaceUpdateEleState(int state)
{
SendMessage(GetDlgItem (form_base->hDlg, IDC_MYBATTERY),
MSG_SET_STATUS,(WPARAM)state,0);
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_static[i].idc != 0; i++) {
ctrls_static[i].font = font20;
createMyStatic(hDlg,&ctrls_static[i]);
}
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
createMyButton(hDlg,&ctrls_button[i]);
}
for (i=0; ctrls_status[i].idc != 0; i++) {
createMyStatus(hDlg,&ctrls_status[i]);
}
for (i=0; ctrls_battery[i].idc != 0; i++) {
ctrls_battery[i].font = font22;
if (sensor) {
ctrls_battery[i].ele_quantity = sensor->getElePower();
ctrls_battery[i].state = sensor->getEleState();
}
createMyBattery(hDlg,&ctrls_battery[i]);
}
if (sensor) {
sensor->interface->uiUpadteElePower = interfaceUpdateElePower;
sensor->interface->uiUpadteEleState = interfaceUpdateEleState;
}
updateNetwork();
updateTime();
updateSdcard();
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formMainProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ---------------------------------------------------------------------------*/
static int formMainProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case MSG_INITDIALOG:
{
Screen.hMainWnd = hDlg;
} break;
case MSG_TIMER:
{
if (flag_timer_stop)
return 0;
if (wParam == IDC_TIMER_1S) {
formMainTimerProc1s(hDlg);
}
} break;
case MSG_ENABLE_WINDOW:
enableAutoClose();
break;
case MSG_DISABLE_WINDOW:
flag_timer_stop = 1;
break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormMain(HWND hMainWnd,void (*callback)(void))
{
HWND Form = Screen.Find(form_base_priv.name);
my_video->showLocalVideo();
if(Form) {
ShowWindow(Form,SW_SHOWNORMAL);
Screen.setCurrent(form_base_priv.name);
} else {
if (bmp_load_finished == 0) {
// topMessage(hMainWnd,TOPBOX_ICON_LOADING,NULL );
return 0;
}
form_base_priv.callBack = callback;
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
int formCreateCaputure(int count)
{
createFormVideo(0,FORM_VIDEO_TYPE_CAPTURE,enableAutoClose,count);
}
<file_sep>/src/app/my_video.h
/*
* =============================================================================
*
* Filename: my_video.h
*
* Description: 视频接口,所有功能控制接口
*
* Version: 1.0
* Created: 2019-06-19 10:20:06
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_VIDEO_H
#define _MY_VIDEO_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
enum HangupType{ // 挂机方式
HANGUP_TYPE_BUTTON, // 手动点击挂机
HANGUP_TYPE_OVERTIME_ANSWER, // 接听后超时挂机
HANGUP_TYPE_OVERTIME_UNANSWER, // 未接听超时挂机
HANGUP_TYPE_PEER, // 对方挂机
};
typedef struct _MyVideo {
void (*showLocalVideo)(void); // 显示本地视频
void (*showPeerVideo)(void); // 显示远程视频
void (*hideVideo)(void); // 隐藏视频
int (*faceRegist)( unsigned char *image_buff,
int w,int h,
char *id,char *nick_name,char *url);// 注册人脸
void (*faceDelete)(char *id); // 删除人脸
int (*faceRecognizer)( unsigned char *image_buff,
int w,int h,
int *age,int *sex);// 识别人脸
void (*capture)(int type,int count,char *nick_name,char *user_id);
int (*recordStart)(int type); // 返回0启动失败 1启动成功
void (*recordWriteCallback)(char *data,int size);
void (*recordStop)(void);
void (*videoCallOut)(char *user_id);
void (*videoCallOutAll)(void);
void (*videoCallIn)(char *user_id);
void (*videoAnswer)(int dir,int dev_type); // dir 0本机接听 1对方接听
void (*videoHangup)(enum HangupType hangup_type); // 0对方挂机 1本机挂机
int (*videoGetCallTime)(void);
int (*videoGetRecordTime)(void);
int (*update)(int type,char *ip,int port,char *file_path); // 升级
int (*delaySleepTime)(int type); // 延长睡眠时间0短 1长
int (*isVideoOn)(void); // 是否在对讲过程,包括呼叫过程,对讲过程
int (*isTalking)(void); // 是否正在通话
void (*resetCallTime)(int); // 重置剩余通话时间
}MyVideo;
extern MyVideo *my_video;
void myVideoInit(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/gui/form_poweroff.c
/*
* =============================================================================
*
* Filename: FormPowerOff.c
*
* Description: 关机界面
*
* Version: 1.0
* Created: 2016-02-23 15:32:24
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <time.h>
#include <string.h>
#include "externfunc.h"
#include "debug.h"
#include "screen.h"
#include "config.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formPoweroffProc(HWND hWnd, int message, WPARAM wParam, LPARAM lParam);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
enum {
IDC_TIMER_1S = IDC_FORM_POWEROFF_STATR,
IDC_CONTTENT,
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static MY_CTRLDATA ChildCtrls [] = {
STATIC_LB(0,280,1024,40,IDC_CONTTENT,"正在关机...",&font22,0xffffff),
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
WS_EX_NONE ,//| WS_EX_AUTOSECONDARYDC,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "FPoweroff",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formPoweroffProc,
.dlgInitParam = &DlgInitParam,
};
static FormBase* form_base = NULL;
/* ---------------------------------------------------------------------------*/
/**
* @brief formPoweroffProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ---------------------------------------------------------------------------*/
static int formPoweroffProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case MSG_TIMER:
{
if (wParam == IDC_TIMER_1S) {
return 0;
}
} break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormPowerOff(HWND hMainWnd)
{
HWND Form = Screen.Find(form_base_priv.name);
if(Form) {
ShowWindow(Form,SW_SHOWNORMAL);
Screen.setCurrent(form_base_priv.name);
} else {
ShowWindow(Form,SW_SHOWNORMAL);
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
int createFormPowerOffLowPower(void)
{
createFormPowerOff(0);
SendMessage(GetDlgItem(form_base->hDlg,IDC_CONTTENT),MSG_SETTEXT,0,(LPARAM)"电量过低,即将关机,请及时充电...");
}
int createFormPowerOffCammerError(void)
{
createFormPowerOff(0);
SendMessage(GetDlgItem(form_base->hDlg,IDC_CONTTENT),MSG_SETTEXT,0,(LPARAM)"镜头接线异常,即将关机,请接好后再重新开机...");
}
int createFormPowerOffCammerErrorSleep(void)
{
createFormPowerOff(0);
SendMessage(GetDlgItem(form_base->hDlg,IDC_CONTTENT),MSG_SETTEXT,0,(LPARAM)"镜头接线异常,请断开电源并长按关机键关机,接好镜头后再重新开机...");
}
int createFormPowerOffSleep(void)
{
createFormPowerOff(0);
SendMessage(GetDlgItem(form_base->hDlg,IDC_CONTTENT),MSG_SETTEXT,0,(LPARAM)"系统即将进入睡眠...");
}
int createFormPowerOffReboot(void)
{
createFormPowerOff(0);
SendMessage(GetDlgItem(form_base->hDlg,IDC_CONTTENT),MSG_SETTEXT,0,(LPARAM)"系统即将重启...");
}
<file_sep>/module/updater/verify/crc/crc32.h
#ifndef _RK_CRC32_H_
#define _RK_CRC32_H_
class RKCRC
{
public:
static unsigned int gTable_Crc32[256];
static unsigned int CRC_32( unsigned char * aData, unsigned int aSize );
RKCRC();
~RKCRC();
};
#endif
<file_sep>/src/app/video/process/display_process.h
#ifndef __DISPLAY_PROCESS_H_
#define __DISPLAY_PROCESS_H_
#include <CameraHal/StrmPUBase.h>
#include <rk_fb/rk_fb.h>
#include <rk_rga/rk_rga.h>
typedef void (*DecCallbackFunc)(void *data,int *size);
class DisplayProcess : public StreamPUBase {
public:
DisplayProcess();
virtual ~DisplayProcess();
bool processFrame(std::shared_ptr<BufferBase> input,
std::shared_ptr<BufferBase> output) override;
void setVideoBlack(void);
void showLocalVideo(void);
void showPeerVideo(int w,int h,DecCallbackFunc decCallBack);
void capture(char *file_name);
bool start_dec(void) const {
return start_dec_;
};
int getWidth(void) const {
return width_;
}
int getHeight(void) const {
return height_;
}
int getCammerState(void) const {
return cammer_state_;
}
void setCammerState(int state) {
cammer_state_ = state;
}
DecCallbackFunc decCallback(void) const {
return decCallback_;
};
private:
int rga_fd;
bool start_dec_;
int width_;
int height_;
int cammer_state_; // 摄像头状态 1正常 0异常
DecCallbackFunc decCallback_;
};
#endif // __DISPLAY_PROCESS_H_
<file_sep>/src/app/video/h264_enc_dec/mpi_enc_api.c
/*
* =============================================================================
*
* Filename: mpi_enc_api.c
*
* Description: h264编码rkmpp
*
* Version: 1.0
* Created: 2019-06-20 17:32:29
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#define MODULE_TAG "mpi_enc_test"
#include <string.h>
#include <mpp/rk_mpi.h>
#include <mpp/mpp_log.h>
#include <mpi/mpp_mem.h>
#include <mpi/mpp_env.h>
#include <mpi/mpp_time.h>
#include <mpi/mpp_common.h>
#include "utils.h"
#include "mpi_enc_api.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
typedef struct {
MppCodingType type;
RK_U32 width;
RK_U32 height;
MppFrameFormat format;
} MpiEncTestCmd;
typedef struct {
// global flow control flag
RK_U32 frm_eos;
RK_U32 pkt_eos;
RK_U32 frame_count;
RK_U64 stream_size;
// src and dst
FILE *fp_input;
FILE *fp_output;
// base flow context
MppCtx ctx;
MppApi *mpi;
MppEncPrepCfg prep_cfg;
MppEncRcCfg rc_cfg;
MppEncCodecCfg codec_cfg;
// input / output
MppBuffer frm_buf;
MppEncSeiMode sei_mode;
// paramter for resource malloc
RK_U32 width;
RK_U32 height;
RK_U32 hor_stride;
RK_U32 ver_stride;
MppFrameFormat fmt;
MppCodingType type;
// resources
size_t frame_size;
/* NOTE: packet buffer may overflow */
size_t packet_size;
// rate control runtime parameter
RK_S32 gop;
RK_S32 fps;
RK_S32 bps;
} MpiEncTestData;
typedef struct _H264EncodePriv{
unsigned char *sps_pps_head;
int sps_pps_head_size;
MpiEncTestData *p;
}H264EncodePriv;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
H264Encode *my_h264enc;
static OptionInfo mpi_enc_cmd[] = {
{"i", "input_file", "input bitstream file"},
{"o", "output_file", "output bitstream file, "},
{"w", "width", "the width of input picture"},
{"h", "height", "the height of input picture"},
{"f", "format", "the format of input picture"},
{"t", "type", "output stream coding type"},
{"n", "max frame number", "max encoding frame number"},
};
static MPP_RET test_ctx_init(MpiEncTestData **data, MpiEncTestCmd *cmd)
{
MpiEncTestData *p = NULL;
MPP_RET ret = MPP_OK;
if (!data || !cmd) {
mpp_err_f("invalid input data %p cmd %p\n", data, cmd);
return MPP_ERR_NULL_PTR;
}
p = mpp_calloc(MpiEncTestData, 1);
if (!p) {
mpp_err_f("create MpiEncTestData failed\n");
ret = MPP_ERR_MALLOC;
goto RET;
}
// get paramter from cmd
p->width = cmd->width;
p->height = cmd->height;
p->hor_stride = MPP_ALIGN(cmd->width, 16);
p->ver_stride = MPP_ALIGN(cmd->height, 16);
p->fmt = cmd->format;
p->type = cmd->type;
// update resource parameter
if (p->fmt <= MPP_FMT_YUV420SP_VU)
p->frame_size = p->hor_stride * p->ver_stride * 3 / 2;
else if (p->fmt <= MPP_FMT_YUV422_UYVY) {
// NOTE: yuyv and uyvy need to double stride
p->hor_stride *= 2;
p->frame_size = p->hor_stride * p->ver_stride;
} else
p->frame_size = p->hor_stride * p->ver_stride * 4;
p->packet_size = p->width * p->height;
RET:
*data = p;
return ret;
}
static MPP_RET test_ctx_deinit(MpiEncTestData **data)
{
MpiEncTestData *p = NULL;
if (!data) {
mpp_err_f("invalid input data %p\n", data);
return MPP_ERR_NULL_PTR;
}
p = *data;
if (p) {
MPP_FREE(p);
*data = NULL;
}
return MPP_OK;
}
static MPP_RET test_mpp_setup(MpiEncTestData *p)
{
MPP_RET ret;
MppApi *mpi;
MppCtx ctx;
MppEncCodecCfg *codec_cfg;
MppEncPrepCfg *prep_cfg;
MppEncRcCfg *rc_cfg;
if (NULL == p)
return MPP_ERR_NULL_PTR;
mpi = p->mpi;
ctx = p->ctx;
codec_cfg = &p->codec_cfg;
prep_cfg = &p->prep_cfg;
rc_cfg = &p->rc_cfg;
/* setup default parameter */
p->fps = 30;
p->gop = 10;
p->bps = p->width * p->height / 8 * p->fps;
prep_cfg->change = MPP_ENC_PREP_CFG_CHANGE_INPUT |
MPP_ENC_PREP_CFG_CHANGE_ROTATION |
MPP_ENC_PREP_CFG_CHANGE_FORMAT;
prep_cfg->width = p->width;
prep_cfg->height = p->height;
prep_cfg->hor_stride = p->hor_stride;
prep_cfg->ver_stride = p->ver_stride;
prep_cfg->format = p->fmt;
prep_cfg->rotation = MPP_ENC_ROT_0;
ret = mpi->control(ctx, MPP_ENC_SET_PREP_CFG, prep_cfg);
if (ret) {
mpp_err("mpi control enc set prep cfg failed ret %d\n", ret);
goto RET;
}
rc_cfg->change = MPP_ENC_RC_CFG_CHANGE_ALL;
rc_cfg->rc_mode = MPP_ENC_RC_MODE_CBR;
rc_cfg->quality = MPP_ENC_RC_QUALITY_MEDIUM;
if (rc_cfg->rc_mode == MPP_ENC_RC_MODE_CBR) {
/* constant bitrate has very small bps range of 1/16 bps */
rc_cfg->bps_target = p->bps;
rc_cfg->bps_max = p->bps * 17 / 16;
rc_cfg->bps_min = p->bps * 15 / 16;
} else if (rc_cfg->rc_mode == MPP_ENC_RC_MODE_VBR) {
if (rc_cfg->quality == MPP_ENC_RC_QUALITY_CQP) {
/* constant QP does not have bps */
rc_cfg->bps_target = -1;
rc_cfg->bps_max = -1;
rc_cfg->bps_min = -1;
} else {
/* variable bitrate has large bps range */
rc_cfg->bps_target = p->bps;
rc_cfg->bps_max = p->bps * 17 / 16;
rc_cfg->bps_min = p->bps * 1 / 16;
}
}
/* fix input / output frame rate */
rc_cfg->fps_in_flex = 0;
rc_cfg->fps_in_num = p->fps;
rc_cfg->fps_in_denorm = 1;
rc_cfg->fps_out_flex = 0;
rc_cfg->fps_out_num = p->fps;
rc_cfg->fps_out_denorm = 1;
rc_cfg->gop = p->gop;
rc_cfg->skip_cnt = 0;
mpp_log("%s() bps %d fps %d gop %d\n",__func__,
rc_cfg->bps_target, rc_cfg->fps_out_num, rc_cfg->gop);
ret = mpi->control(ctx, MPP_ENC_SET_RC_CFG, rc_cfg);
if (ret) {
mpp_err("mpi control enc set rc cfg failed ret %d\n", ret);
goto RET;
}
codec_cfg->coding = p->type;
switch (codec_cfg->coding) {
case MPP_VIDEO_CodingAVC : {
codec_cfg->h264.change = MPP_ENC_H264_CFG_CHANGE_PROFILE |
MPP_ENC_H264_CFG_CHANGE_ENTROPY |
MPP_ENC_H264_CFG_CHANGE_TRANS_8x8;
/*
* H.264 profile_idc parameter
* 66 - Baseline profile
* 77 - Main profile
* 100 - High profile
*/
codec_cfg->h264.profile = 100;
/*
* H.264 level_idc parameter
* 10 / 11 / 12 / 13 - qcif@15fps / cif@7.5fps / cif@15fps / cif@30fps
* 20 / 21 / 22 - cif@30fps / half-D1@@25fps / D1@12.5fps
* 30 / 31 / 32 - D1@25fps / 720p@30fps / 720p@60fps
* 40 / 41 / 42 - 1080p@30fps / 1080p@30fps / 1080p@60fps
* 50 / 51 / 52 - 4K@30fps
*/
codec_cfg->h264.level = 31;
codec_cfg->h264.entropy_coding_mode = 1;
codec_cfg->h264.cabac_init_idc = 0;
codec_cfg->h264.transform8x8_mode = 1;
} break;
case MPP_VIDEO_CodingMJPEG : {
codec_cfg->jpeg.change = MPP_ENC_JPEG_CFG_CHANGE_QP;
codec_cfg->jpeg.quant = 10;
} break;
case MPP_VIDEO_CodingVP8 : {
} break;
case MPP_VIDEO_CodingHEVC : {
codec_cfg->h265.change = MPP_ENC_H265_CFG_INTRA_QP_CHANGE;
codec_cfg->h265.intra_qp = 26;
} break;
default : {
mpp_err_f("support encoder coding type %d\n", codec_cfg->coding);
} break;
}
ret = mpi->control(ctx, MPP_ENC_SET_CODEC_CFG, codec_cfg);
if (ret) {
mpp_err("mpi control enc set codec cfg failed ret %d\n", ret);
goto RET;
}
/* optional */
p->sei_mode = MPP_ENC_SEI_MODE_ONE_FRAME;
ret = mpi->control(ctx, MPP_ENC_SET_SEI_CFG, &p->sei_mode);
if (ret) {
mpp_err("mpi control enc set sei cfg failed ret %d\n", ret);
goto RET;
}
RET:
return ret;
}
static int mpi_enc_test(H264Encode *This,MpiEncTestCmd *cmd)
{
MPP_RET ret = MPP_OK;
MppApi *mpi;
MppCtx ctx;
mpp_log("%s() start\n",__func__);
ret = test_ctx_init(&This->priv->p, cmd);
if (ret) {
mpp_err_f("test data init failed ret %d\n", ret);
goto MPP_TEST_OUT;
}
MpiEncTestData *p = This->priv->p;
ret = mpp_buffer_get(NULL, &p->frm_buf, p->frame_size);
if (ret) {
mpp_err_f("failed to get buffer for input frame ret %d\n", ret);
goto MPP_TEST_OUT;
}
mpp_log("%s() encoder test start w %d h %d type %d\n",__func__,
p->width, p->height, p->type);
// encoder demo
ret = mpp_create(&p->ctx, &p->mpi);
if (ret) {
mpp_err("mpp_create failed ret %d\n", ret);
goto MPP_TEST_OUT;
}
ret = mpp_init(p->ctx, MPP_CTX_ENC, p->type);
if (ret) {
mpp_err("mpp_init failed ret %d\n", ret);
goto MPP_TEST_OUT;
}
ret = test_mpp_setup(p);
if (ret) {
mpp_err_f("test mpp setup failed ret %d\n", ret);
goto MPP_TEST_OUT;
}
mpi = p->mpi;
ctx = p->ctx;
// H264格式并且为第一帧时,提取sps/pps
if (p->type == MPP_VIDEO_CodingAVC) {
MppPacket packet = NULL;
ret = mpi->control(ctx, MPP_ENC_GET_EXTRA_INFO, &packet);
if (ret) {
mpp_err("mpi control enc get extra info failed\n");
goto MPP_TEST_OUT;
}
/* get and write sps/pps for H.264 */
if (packet) {
void *ptr = mpp_packet_get_pos(packet);
This->priv->sps_pps_head_size = mpp_packet_get_length(packet);
This->priv->sps_pps_head = (unsigned char *)malloc(This->priv->sps_pps_head_size);
memcpy(This->priv->sps_pps_head,ptr,This->priv->sps_pps_head_size);
}
}
MPP_TEST_OUT:
return 1;
}
static int mpiH264EncEncode(H264Encode *This,
unsigned char *in_data,
unsigned char **out_data,
int *frame_type)
{
MPP_RET ret;
MppApi *mpi;
MppCtx ctx;
MpiEncTestData *p = This->priv->p;
*frame_type = 0;
if (NULL == p) {
return 0;
}
mpi = p->mpi;
ctx = p->ctx;
MppFrame frame = NULL;
MppPacket packet = NULL;
void *buf = mpp_buffer_get_ptr(p->frm_buf);
memcpy(buf,in_data,p->frame_size);
ret = mpp_frame_init(&frame);
if (ret) {
mpp_err_f("mpp_frame_init failed\n");
goto RET;
}
mpp_frame_set_width(frame, p->width);
mpp_frame_set_height(frame, p->height);
mpp_frame_set_hor_stride(frame, p->hor_stride);
mpp_frame_set_ver_stride(frame, p->ver_stride);
mpp_frame_set_fmt(frame, p->fmt);
mpp_frame_set_buffer(frame, p->frm_buf);
mpp_frame_set_eos(frame, p->frm_eos);
ret = mpi->encode_put_frame(ctx, frame);
if (ret) {
mpp_err("mpp encode put frame failed\n");
goto RET;
}
ret = mpi->encode_get_packet(ctx, &packet);
if (ret) {
mpp_err("mpp encode get packet failed\n");
goto RET;
}
size_t len = 0;
if (packet) {
// write packet to file here
void *ptr = mpp_packet_get_pos(packet);
int len = mpp_packet_get_length(packet);
ret = len;
p->pkt_eos = mpp_packet_get_eos(packet);
unsigned char *head = ptr;
int I_Frame = 0;
if (head[0] == 0 && head[1] == 0 && head[2] == 1) {
if (head[3] == 0x65) {
I_Frame = 1;
}
}
if (I_Frame) {
*out_data = (unsigned char*) malloc(This->priv->sps_pps_head_size + len);
memcpy(*out_data,This->priv->sps_pps_head,This->priv->sps_pps_head_size);
memcpy(&((*out_data)[This->priv->sps_pps_head_size]),ptr,len);
*frame_type = 1;
} else {
*out_data = (unsigned char*) malloc(len);
memcpy(*out_data,ptr,len);
*frame_type = 0;
}
mpp_packet_deinit(&packet);
// mpp_log_f("encoded %s frame %d size %d\n", I_Frame ? "I":"P",p->frame_count, len);
p->stream_size += len;
p->frame_count++;
if (p->pkt_eos) {
mpp_log("found last packet\n");
mpp_assert(p->frm_eos);
}
}
RET:
return ret;
}
static void mpiH264EncInit(H264Encode *This,int width,int height)
{
MPP_RET ret = MPP_OK;
MpiEncTestCmd cmd_ctx;
memset(&cmd_ctx, 0, sizeof(MpiEncTestCmd));
cmd_ctx.type = MPP_VIDEO_CodingAVC;
cmd_ctx.width = width;
cmd_ctx.height = height;
cmd_ctx.format = MPP_FMT_YUV420SP;
mpp_env_set_u32("mpi_debug", 0x0);
mpi_enc_test(This,&cmd_ctx);
}
static void mpiH264EncUnInit(H264Encode *This)
{
MpiEncTestData *p = This->priv->p;
if (This->priv->sps_pps_head)
free(This->priv->sps_pps_head);
This->priv->sps_pps_head = NULL;
int ret = p->mpi->reset(p->ctx);
if (ret) {
mpp_err("mpi->reset failed\n");
}
if (p->ctx) {
mpp_destroy(p->ctx);
p->ctx = NULL;
}
if (p->frm_buf) {
mpp_buffer_put(p->frm_buf);
p->frm_buf = NULL;
}
// if (MPP_OK == ret)
// mpp_log("%s()success total frame %d bps %lld\n",__func__,
// p->frame_count, (RK_U64)((p->stream_size * 8 * p->fps) / p->frame_count));
// else
// mpp_err("%s() failed ret %d\n",__func__, ret);
test_ctx_deinit(&This->priv->p);
}
void myH264EncInit(void)
{
my_h264enc = (H264Encode *)calloc(1,sizeof(H264Encode));
my_h264enc->priv = (H264EncodePriv *)calloc(1,sizeof(H264EncodePriv));
my_h264enc->init = mpiH264EncInit;
my_h264enc->unInit = mpiH264EncUnInit;
my_h264enc->encode = mpiH264EncEncode;
}
<file_sep>/src/app/ucpaas/ucpaas.c
/*
* =============================================================================
*
* Filename: protocol_ucpaas.c
*
* Description: 云之讯对讲协议
*
* Version: 1.0
* Created: 2019-06-04 16:09:13
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
#include "ucpaas.h"
#include "sql_handle.h"
#include "thread_helper.h"
#include "ucpaas/UCSService.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define DPRINT(...) \
do { \
printf("\033[1;33m"); \
printf("[UCPASS->%s,%d]",__func__,__LINE__); \
printf(__VA_ARGS__); \
printf("\033[0m"); \
} while (0)
typedef struct _DebugInfo {
int opt;
const char *content;
}DebugInfo;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static Callbacks call_backs;
static int g_externalAVEn = 1;
static int connect_state = 0;
static int call_status = 0;
static unsigned char *rec_buf = NULL;
static unsigned int rec_buf_len = 0;
static int send_for_reciev_video = 0; // 为了接收视频,发送视频数据保持连接
static const char * ucDebugInfo(int ev_reason)
{
static DebugInfo debug_info[] = {
{eUCS_REASON_SUCCESS,"eUCS_REASON_SUCCESS"},
{eUCS_REASON_TCP_CONNECTED,"eUCS_REASON_TCP_CONNECTED"},
{eUCS_REASON_TCP_RECONNECTED,"eUCS_REASON_TCP_RECONNECTED"},
{eUCS_REASON_TCP_DISCONNECTED,"eUCS_REASON_TCP_DISCONNECTED"},
{eUCS_REASON_TCP_SEND,"eUCS_REASON_TCP_SEND"},
{eUCS_REASON_TCP_RECV,"eUCS_REASON_TCP_RECV"},
{eUCS_REASON_TCP_TRANS_EMPTY,"eUCS_REASON_TCP_TRANS_EMPTY"},
{eUCS_REASON_TCP_TRANS_TARGET_UNEXIST,"eUCS_REASON_TCP_TRANS_TARGET_UNEXIST"},
{eUCS_REASON_TCP_TRANS_TARGET_OFFLINE,"eUCS_REASON_TCP_TRANS_TARGET_OFFLINE"},
{eUCS_REASON_TCP_TRANS_PROXY_ERROR,"eUCS_REASON_TCP_TRANS_PROXY_ERROR"},
{eUCS_REASON_TCP_TRANS_SEND_TIMEOUT,"eUCS_REASON_TCP_TRANS_SEND_TIMEOUT"},
{eUCS_REASON_LOGIN_SUCCESS,"eUCS_REASON_LOGIN_SUCCESS"},
{eUCS_REASON_TOKEN_INVALID,"eUCS_REASON_TOKEN_INVALID"},
{eUCS_REASON_LOGIN_ARG_ERR,"eUCS_REASON_LOGIN_ARG_ERR"},
{eUCS_REASON_LOGIN_SYS_ERR,"eUCS_REASON_LOGIN_SYS_ERR"},
{eUCS_REASON_LOGIN_PWD_ERR,"eUCS_REASON_LOGIN_PWD_ERR"},
{eUCS_REASON_INVALID_PROXYS_NUM,"eUCS_REASON_INVALID_PROXYS_NUM"},
{eUCS_REASON_RINGING,"eUCS_REASON_RINGING"},
{eUCS_REASON_CONNECTING,"eUCS_REASON_CONNECTING"},
{eUCS_REASON_INVALID_CALLED,"eUCS_REASON_INVALID_CALLED"},
{eUCS_REASON_CALLED_OFFLINE,"eUCS_REASON_CALLED_OFFLINE"},
{eUCS_REASON_CALLED_BUSY,"eUCS_REASON_CALLED_BUSY"},
{eUCS_REASON_CALLED_REJECT,"eUCS_REASON_CALLED_REJECT"},
{eUCS_REASON_CALLED_NO_ANSWER,"eUCS_REASON_CALLED_NO_ANSWER"},
{eUCS_REASON_CALLED_FROZEN,"eUCS_REASON_CALLED_FROZEN"},
{eUCS_REASON_CALLER_FROZEN,"eUCS_REASON_CALLER_FROZEN"},
{eUCS_REASON_CALLER_EXPIRED,"eUCS_REASON_CALLER_EXPIRED"},
{eUCS_REASON_NO_BALANCE,"eUCS_REASON_NO_BALANCE"},
{eUCS_REASON_MSG_TIMEOUT,"eUCS_REASON_MSG_TIMEOUT"},
{eUCS_REASON_BLACKlIST,"eUCS_REASON_BLACKlIST"},
{eUCS_REASON_HANGUP_BYPEER,"eUCS_REASON_HANGUP_BYPEER"},
{eUCS_REASON_HANGUP_MYSELF,"eUCS_REASON_HANGUP_MYSELF"},
{eUCS_REASON_MEDIA_NOT_ACCEPT,"eUCS_REASON_MEDIA_NOT_ACCEPT"},
{eUCS_REASON_RTPP_TIMEOUT,"eUCS_REASON_RTPP_TIMEOUT"},
{eUCS_REASON_MEDIA_UPDATE_FAILED,"eUCS_REASON_MEDIA_UPDATE_FAILED"},
{eUCS_REASON_CALLER_CANCEL,"eUCS_REASON_CALLER_CANCEL"},
{eUCS_REASON_FORBIDDEN,"eUCS_REASON_FORBIDDEN"},
{eUCS_REASON_RTP_RECEIVED_TIMEOUT,"eUCS_REASON_RTP_RECEIVED_TIMEOUT"},
{eUCS_REASON_CALLID_NOT_EXIST,"eUCS_REASON_CALLID_NOT_EXIST"},
{eUCS_REASON_NOT_LOGGED_IN,"eUCS_REASON_NOT_LOGGED_IN"},
{eUCS_REASON_INTERNAL_SRV_ERROR,"eUCS_REASON_INTERNAL_SRV_ERROR"},
};
int i;
for (i=0; i<sizeof(debug_info)/sizeof(DebugInfo); i++) {
if (ev_reason == debug_info[i].opt)
return debug_info[i].content;
}
}
// UCS connect status callback
static void connect_event_cb(int ev_reason)
{
DPRINT("ev_reason[%s]\n", ucDebugInfo(ev_reason));
if (ev_reason == eUCS_REASON_LOGIN_SUCCESS) {
connect_state = 1;
}
}
// UCS dailing out failed
static void dial_failed_cb(const char* callid, int reason)
{
DPRINT("callid[%s] reason[%s]\n", callid, ucDebugInfo(reason));
int result = 0;
if (call_backs.dialFail)
call_backs.dialFail(&result);
call_status = 0;
}
// call alerting
static void on_alerting_cb(const char* callid)
{
DPRINT("callid[%s]\n", callid);
if (call_backs.dialRet)
call_backs.dialRet((void *)callid);
}
// new call incoming
static void on_incomingcall_cb(const char* callid, int calltype,
const char* caller_uid, const char* caller_name,
const char* userdata)
{
DPRINT("callid[%s] calltype[%d], caller_uid[%s] caller_name[%s] userdata[%s]\n",
callid, calltype, caller_uid, caller_name, userdata);
if (call_backs.incomingCall)
call_backs.incomingCall((void *)caller_uid);
call_status = 1;
}
// call answer
static void on_answer_cb(const char* callid)
{
DPRINT("callid[%s]\n", callid);
if (call_backs.answer)
call_backs.answer((void *)callid);
}
// call hangup
static void on_hangup_cb(const char* callid, int reason)
{
DPRINT("callid[%s] reason[%s]\n", callid,ucDebugInfo(reason));
call_status = 0;
send_for_reciev_video = 0;
int type = 0;
if (reason == eUCS_REASON_HANGUP_MYSELF)
type = 1;
else if (reason == eUCS_REASON_HANGUP_BYPEER)
type = 2;
if (call_backs.hangup)
call_backs.hangup(&type);
}
// received dtmf
static void received_dtmf_cb(int dtmf_code)
{
DPRINT("dtmf_code[%d]\n", dtmf_code);
}
// network quality report between call session
static void network_state_report_cb(int reason, const char* netstate)
{
DPRINT("reason[%s] netstate[%s]\n", ucDebugInfo(reason), netstate);
}
// UCS through data received callback
static void transdata_received_cb(const char* from_userId,
const char* callid,
const char* trans_data)
{
if ( NULL != trans_data)
{
if (call_backs.receivedCmd)
call_backs.receivedCmd(from_userId,(void *) trans_data);
DPRINT("transdata_received_cb: trans_data[%s]\n", trans_data);
}
}
static void transdata_send_result_cb(int err_code)
{
DPRINT("transdata_send_result_cb: err_code[%s]\n",ucDebugInfo(err_code) );
if (call_backs.sendCmd)
call_backs.sendCmd(&err_code);
}
// UCS invoke it to change video stream
static void set_video_framerate_cb(unsigned int target_width, unsigned int target_height,
unsigned int frame_rate, unsigned int bitrate)
{
DPRINT("set_video_framerate_cb: resolution[%dx%d fps[%d] bitrate[%d]\n",
target_width, target_height, frame_rate, bitrate);
}
// UCS init external playout device with given parameters
// sample_rate -- playout audio sample rate, 16k
// bytes_per_sample -- bytes of per sample, always 2 bytes = 16bits
// num_of_channels -- number of playout channels, always = 1
static void init_playout_cb(unsigned int sample_rate,
unsigned int bytes_per_sample,
unsigned int num_of_channels)
{
DPRINT("rate:%d,sample:%d,channle:%d \n",
sample_rate,
bytes_per_sample,
num_of_channels);
if (call_backs.initAudio)
call_backs.initAudio(8000,16,2);
}
// UCS init external recording device with given parameters
// sample_rate -- recording audio sample rate, 16000
// bytes_per_sample -- bytes of per sample, always 2 bytes = 16bits
// num_of_channels -- number of recording channels, always = 1
static void init_recording_cb(unsigned int sample_rate,
unsigned int bytes_per_sample,
unsigned int num_of_channels)
{
DPRINT("rate:%d,sample:%d,channle:%d \n",
sample_rate,
bytes_per_sample,
num_of_channels);
if (call_backs.startRecord)
call_backs.startRecord(sample_rate,bytes_per_sample,num_of_channels);
}
// UCS read recording 10ms pcm data from external audio device
// audio_data -- recording pcm data
// size -- want to read data len
static int read_recording_data_cb(char * audio_data,
unsigned int size)
{
if (call_backs.recording)
call_backs.recording(audio_data,size);
return 0;
}
// UCS write playout 10ms pcm data to external audio device
// audio_data -- playout data for external audio device
// size -- playout data length
static int write_playout_data_cb(const char* audio_data,
unsigned int size)
{
if (call_backs.playAudio)
call_backs.playAudio(audio_data,size);
return 0;
}
static int TUCS_Init()
{
char version[UCS_MAX_VERSION_STR_LEN] = { 0 };
UCS_cb_vtable_t vtable;
memset(&vtable, 0x00, sizeof(UCS_cb_vtable_t));
vtable.connect_cb = connect_event_cb;
vtable.dial_failed_cb = dial_failed_cb;
vtable.on_alerting_cb = on_alerting_cb;
vtable.on_answer_cb = on_answer_cb;
vtable.on_incomingcall_cb = on_incomingcall_cb;
vtable.on_hangup_cb = on_hangup_cb;
vtable.received_dtmf_cb = received_dtmf_cb;
vtable.transdata_received_cb = transdata_received_cb;
vtable.transdata_send_result_cb = transdata_send_result_cb;
vtable.set_video_framerate_cb = set_video_framerate_cb;
vtable.init_playout_cb = init_playout_cb;
vtable.init_recording_cb = init_recording_cb;
vtable.write_data_cb = write_playout_data_cb;
vtable.read_data_cb = read_recording_data_cb;
UCS_RegisterCallbackVtable(&vtable);
if (UCS_Init() < 0) {
DPRINT("ucs init failed.\n");
return -1;
}
UCS_SetLogEnable(0, NULL);
UCS_GetVersion(version);
DPRINT("ucpaas version %s\n",version);
return 0;
}
static int TUCS_Destory()
{
return UCS_Destory();
}
void ucsDial(char *user_id)
{
if (connect_state == 0)
return;
UCS_Dial(user_id, eUCS_CALL_TYPE_VIDEO_CALL);
call_status = 1;
}
void ucsAnswer(void)
{
if (connect_state == 0)
return;
UCS_CallAnswer();
}
void ucsHangup(void)
{
if (connect_state == 0)
return;
if (call_status == 0)
return;
UCS_CallHangUp();
}
/* ---------------------------------------------------------------------------*/
/**
* @brief ucsSendCmd 云之讯cmd会将cmd内容打包成json,所以传入的cmd碰到"需要加转义
* 字符,例如:
*
* {\\\"messageType\\\":%d,\\\"deviceType\\\":%d,\\\"deviceNumber\\\":\\\"%s\\\"}
*
* @param cmd
* @param user_id
*/
/* ---------------------------------------------------------------------------*/
void ucsSendCmd(char *cmd,char *user_id)
{
if (connect_state == 0)
return;
UCS_SendTransData(0, user_id, cmd, strlen(cmd));
}
void ucsSendVideo(const unsigned char* frameData, const unsigned int dataLen)
{
if (connect_state == 0)
return;
// DPRINT("send:%d\n", dataLen);
UCS_PushExternalVideoStream(frameData,dataLen);
}
static void* threadSendForRecive(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
send_for_reciev_video = 1;
while (send_for_reciev_video) {
if (rec_buf) {
UCS_PushExternalVideoStream(rec_buf,rec_buf_len);
}
usleep(100000);
}
if (rec_buf) {
free(rec_buf);
rec_buf = NULL;
rec_buf_len = 0;
}
return NULL;
}
void ucsReceiveVideo(unsigned char* frameData,
unsigned int *dataLen,
long long *timeStamp,
int *frameType)
{
if (connect_state == 0)
return;
UCS_get_video_frame(frameData, dataLen,timeStamp,frameType);
if (rec_buf == NULL && *dataLen) {
rec_buf = (unsigned char *)malloc (*dataLen);
rec_buf_len = *dataLen;
memcpy(rec_buf,frameData,*dataLen);
createThread(threadSendForRecive,NULL);
}
}
int ucsConnect(char *user_token)
{
if (connect_state == 1)
return 0;
if (user_token[0] != 0) {
UCS_Connect(user_token);
// test 门口机
// UCS_Connect("<KEY>
return 1;
}
return 0;
}
void ucsDisconnect(void)
{
if (connect_state == 0)
return;
connect_state = 0;
UCS_DisConnect();
}
void registUcpaas(Callbacks *interface)
{
call_backs.dialFail = interface->dialFail;
call_backs.answer = interface->answer;
call_backs.hangup = interface->hangup;
call_backs.dialRet = interface->dialRet;
call_backs.incomingCall = interface->incomingCall;
call_backs.sendCmd = interface->sendCmd;
call_backs.receivedCmd = interface->receivedCmd;
call_backs.initAudio = interface->initAudio;
call_backs.startRecord = interface->startRecord;
call_backs.recording = interface->recording;
call_backs.playAudio = interface->playAudio;
if (TUCS_Init() == 0) {
UCS_SetExtAudioTransEnable(g_externalAVEn);
UCS_SetExtVideoStreamEnable(g_externalAVEn);
UCS_ViERingPreviewEnable(1);
UCS_vqecfg_t vqecfg;
vqecfg.aec_enable = 1;
vqecfg.agc_enable = 1;
vqecfg.ns_enable = 1;
UCS_SetVqeCfg(&vqecfg);
}
}
int unregistUcpaas(void)
{
TUCS_Destory();
}
int ucsConnectState(void)
{
return connect_state;
}
<file_sep>/src/app/video/h264_enc_dec/mpi_dec_api.h
/*
* =============================================================================
*
* Filename: mpi_dec_api.h
*
* Description: mpp api h264解码
*
* Version: 1.0
* Created: 2019-06-20 15:44:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MPI_DEC_API_H
#define _MPI_DEC_API_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
struct _H264DecodePriv;
typedef struct _H264Decode {
struct _H264DecodePriv *priv;
int (*decode)(struct _H264Decode *This,unsigned char *in_data,int in_size,unsigned char *out_data,int *out_w,int *out_h);
int (*init)(struct _H264Decode *This,int w,int h);
int (*unInit)(struct _H264Decode *This);
}H264Decode;
extern H264Decode *my_h264dec;
void myH264DecInit(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/drivers/mp4_muxer/CMakeLists.txt
# 查找当前目录下的所有源文件 并将名称保存到 SRCS_MP4MUXERLIB 变量
set(SRCS_MP4MUXERLIB
mp4_muxer.c
)
# 生成链接库
add_library (mp4_muxer ${SRCS_MP4MUXERLIB})
target_link_libraries(mp4_muxer
mp4v2 faac stdc++
)
<file_sep>/src/drivers/avilib/CMakeLists.txt
# 查找当前目录下的所有源文件 并将名称保存到 SRCS_AVILIB 变量
aux_source_directory(. SRCS_AVILIB)
STRING( REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER_AVILIB ${CMAKE_CURRENT_SOURCE_DIR})
# 生成链接库
add_library (${CURRENT_FOLDER_AVILIB} ${SRCS_AVILIB})
<file_sep>/src/gui/my_controls/my_status.c
/*
* =====================================================================================
*
* Filename: MyStatus.c
*
* Description: 自定义状态
*
* Version: 1.0
* Created: 2015-12-09 16:22:37
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
/* ----------------------------------------------------------------*
* include head files
*-----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include "my_status.h"
#include "debug.h"
#include "cliprect.h"
#include "internals.h"
#include "ctrlclass.h"
/* ----------------------------------------------------------------*
* extern variables declare
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*
* internal functions declare
*-----------------------------------------------------------------*/
static int myctrlControlProc (HWND hwnd, int message, WPARAM wParam, LPARAM lParam);
/* ----------------------------------------------------------------*
* macro define
*-----------------------------------------------------------------*/
#define CTRL_NAME CTRL_MYSTATUS
/* ----------------------------------------------------------------*
* variables define
*-----------------------------------------------------------------*/
MyControls * my_status;
/* ---------------------------------------------------------------------------*/
/**
* @brief myStatusRegist 注册控件
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static BOOL myStatusRegist (void)
{
WNDCLASS WndClass;
WndClass.spClassName = CTRL_NAME;
WndClass.dwStyle = WS_NONE;
WndClass.dwExStyle = WS_EX_NONE;
WndClass.hCursor = GetSystemCursor (IDC_ARROW);
WndClass.iBkColor = 0;
WndClass.WinProc = myctrlControlProc;
return RegisterWindowClass(&WndClass);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myStatusCleanUp 卸载控件
*/
/* ---------------------------------------------------------------------------*/
static void myStatusCleanUp (void)
{
UnregisterWindowClass(CTRL_NAME);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief paint 主要绘图函数
*
* @param hWnd
* @param hdc
*/
/* ---------------------------------------------------------------------------*/
static void paint(HWND hWnd,HDC hdc)
{
#define FILL_BMP_STRUCT(rc,img) rc.left, rc.top,img->bmWidth,img->bmHeight,img
RECT rcClient;
PCONTROL pCtrl;
pCtrl = Control (hWnd);
GetClientRect (hWnd, &rcClient);
if (pCtrl->dwAddData2) {
MyStatusCtrlInfo* pInfo = (MyStatusCtrlInfo*)(pCtrl->dwAddData2);
BITMAP *bmp = pInfo->images + pInfo->level;
if (bmp)
FillBoxWithBitmap(hdc, FILL_BMP_STRUCT(rcClient,bmp));
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myctrlControlProc 控件主回调函数
*
* @param hwnd
* @param message
* @param wParam
* @param lParam
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int myctrlControlProc (HWND hwnd, int message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PCONTROL pCtrl;
DWORD dwStyle;
MyStatusCtrlInfo* pInfo;
pCtrl = Control (hwnd);
pInfo = (MyStatusCtrlInfo*)pCtrl->dwAddData2;
dwStyle = GetWindowStyle (hwnd);
switch (message) {
case MSG_CREATE:
{
MyStatusCtrlInfo* data = (MyStatusCtrlInfo*)pCtrl->dwAddData;
pInfo = (MyStatusCtrlInfo*) calloc (1, sizeof (MyStatusCtrlInfo));
if (pInfo == NULL)
return -1;
memset(pInfo,0,sizeof(MyStatusCtrlInfo));
pInfo->images = data->images;
pInfo->level = data->level;
pInfo->total_level = data->total_level;
pCtrl->dwAddData2 = (DWORD)pInfo;
return 0;
}
case MSG_DESTROY:
free(pInfo);
break;
case MSG_PAINT:
hdc = BeginPaint (hwnd);
paint(hwnd,hdc);
EndPaint (hwnd, hdc);
return 0;
case MSG_MYSTATUS_SET_LEVEL:
pInfo->level = wParam;
InvalidateRect (hwnd, NULL, TRUE);
return 0;
default:
break;
}
return DefaultControlProc (hwnd, message, wParam, lParam);
}
static void myStatusBmpsLoad(void *ctrls,char *path)
{
int i,j;
char image_path[128] = {0};
MyCtrlStatus *controls = (MyCtrlStatus *)ctrls;
for (i=0; controls->idc != 0; i++) {
controls->images = (BITMAP *)calloc(controls->total_level,sizeof(BITMAP));
for (j=0; j<controls->total_level; j++) {
sprintf(image_path,"%s%s-%d.png",path,controls->img_name,j);
bmpLoad(controls->images + j, image_path);
}
controls++;
}
}
static void myStatusBmpsRelease(void *ctrls)
{
int i;
MyCtrlStatus *controls = (MyCtrlStatus *)ctrls;
for (i=0; controls->idc != 0; i++) {
bmpRelease(controls->images + i);
free(controls->images + i);
controls++;
}
}
HWND createMyStatus(HWND hWnd,MyCtrlStatus *ctrl)
{
HWND hCtrl;
int ctrl_w,ctrl_h = 0;
MyStatusCtrlInfo pInfo;
memset(&pInfo,0,sizeof(MyStatusCtrlInfo));
pInfo.level = 0;
pInfo.total_level = ctrl->total_level;
pInfo.images = ctrl->images;
ctrl_w = ctrl->images->bmWidth;
ctrl_h = ctrl->images->bmHeight;
hCtrl = CreateWindowEx(CTRL_NAME,"",WS_VISIBLE|WS_CHILD,WS_EX_TRANSPARENT,
ctrl->idc,ctrl->x,ctrl->y,ctrl_w,ctrl_h, hWnd,(DWORD)&pInfo);
return hCtrl;
}
void initMyStatus(void)
{
my_status = (MyControls *)malloc(sizeof(MyControls));
my_status->regist = myStatusRegist;
my_status->unregist = myStatusCleanUp;
my_status->bmpsLoad = myStatusBmpsLoad;
my_status->bmpsRelease = myStatusBmpsRelease;
}
<file_sep>/module/updater/verify/md5/md5sum.h
#ifndef _RK_MD5_H_
#define _RK_MD5_H_
#define MD5_LEN 32
class RKMD5
{
public:
static int md5sum(char *file_name, char *md5_sum);
static int readmd5sum(char *file_name, char *md5_sum);
RKMD5();
~RKMD5();
};
#endif
<file_sep>/src/drivers/sqlite.c
/*
* =============================================================================
*
* Filename: sqlite.c
*
* Description: 数据库接口
*
* Version: virsion
* Created: 2018-05-22 10:39:45
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "sqlite3.h"
#include "sqlite.h"
#include "externfunc.h"
#include "debug.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
#define SQL_LOCK() pthread_mutex_lock(&Query->sql_lock->mutex)
#define SQL_UNLOCK() pthread_mutex_unlock(&Query->sql_lock->mutex)
struct Sqlite_mutex {
pthread_mutex_t mutex;
};
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
//----------------------------------------------------------------------------
char *strupper(char *pdst,const char *pstr,int Size);
struct SqlitePrivate
{
BOOL Active;
sqlite3 *db;
sqlite3_stmt *ppStmt;
int bind_num;
char **pData;
char *SqlText;
char *pErrMsg;
int FieldCount;
int RecordCount;
int RecNo;
// int LastRowID;
};
//----------------------------------------------------------------------------
static char * strncpytrim(char *pDest,const char *pSrc,int Size)
{
int i = Size;
char *pTmp = pDest;
while(*pSrc && --i) {
*pDest++ = *pSrc++;
}
//去除尾导空格
while(pTmp!=pDest) {
if(*(--pDest)!=32) {
pDest++;
break;
}
}
*pDest = 0;
return pTmp;
}
//----------------------------------------------------------------------------
static char * TField_AsChar(PSQLiteField This,char *Buf,int Size)
{
//
if(!This->Private->Active)
{
Buf[0]=0;
return Buf;
}
if(This->Private->RecNo==0)
{
Buf[0]=0;
return Buf;
}
if(This->Private->pData[This->Private->FieldCount*(This->Private->RecNo)+
This->offset]==NULL) {
Buf[0]=0;
return Buf;
}
strncpytrim(Buf,This->Private->pData[This->Private->FieldCount*(This->Private->RecNo)+
This->offset],Size);
return Buf;
}
//----------------------------------------------------------------------------
static int TField_AsInt(PSQLiteField This)
{
if(!This->Private->Active)
{
return 0;
}
if(This->Private->RecNo==0)
{
return 0;
}
if(This->Private->pData[This->Private->FieldCount*(This->Private->RecNo)+
This->offset]==NULL)
return 0;
return atoi(This->Private->pData[This->Private->FieldCount*(This->Private->RecNo)+
This->offset]);
}
//----------------------------------------------------------------------------
static double TField_AsFloat(PSQLiteField This)
{
if(!This->Private->Active)
{
return 0;
}
if(This->Private->RecNo==0)
{
return 0;
}
if(This->Private->pData[This->Private->FieldCount*(This->Private->RecNo)+
This->offset]==NULL)
return 0;
return atof(This->Private->pData[This->Private->FieldCount*(This->Private->RecNo)+
This->offset]);
}
//----------------------------------------------------------------------------
static void SQLite_Destroy(struct _TSqlite *This)
{
if(This->Private->Active) {
This->Close(This);
}
sqlite3_close(This->Private->db);
if(This->Private->SqlText)
free(This->Private->SqlText);
free(This->Private);
free(This);
}
//----------------------------------------------------------------------------
//打开
static BOOL SQLite_Open(struct _TSqlite *This)
{
int i;
if(This->Private->Active) {
This->Close(This);
}
if(sqlite3_get_table(This->Private->db,This->Private->SqlText,&This->Private->pData,
&This->Private->RecordCount,&This->Private->FieldCount,
&This->Private->pErrMsg)==SQLITE_OK) {
This->Fields = (PSQLiteField)malloc(sizeof(TSQLiteField)*This->Private->FieldCount);
if(This->Fields==NULL) {
// DPRINT("Memory not enough\n");
sqlite3_free_table(This->Private->pData);
This->Private->pData = NULL;
return TRUE;
}
memset(This->Fields,0,sizeof(TSQLiteField)*This->Private->FieldCount);
This->Private->Active = TRUE;
for(i=0;i<This->Private->FieldCount;i++) {
strupper(This->Fields[i].Name,This->Private->pData[i],SQL_NAME_MAX);
This->Fields[i].offset = i;
This->Fields[i].Private = This->Private;
This->Fields[i].AsChar = TField_AsChar;
This->Fields[i].AsInt = TField_AsInt;
This->Fields[i].AsFloat = TField_AsFloat;
}
if(This->Private->FieldCount)
This->Private->RecNo = 1;
else
This->Private->RecNo = 0;
return TRUE;
}
if(This->Private->pErrMsg) {
sqlite3_free(This->Private->pErrMsg);
This->Private->pErrMsg = NULL;
}
return FALSE;
}
//----------------------------------------------------------------------------
//执行
static BOOL SQLite_ExecSQL(struct _TSqlite *This)
{
if(This->Private->Active)
This->Close(This);
if(sqlite3_exec( This->Private->db,This->Private->SqlText,NULL,0,
&This->Private->pErrMsg)==SQLITE_OK) {
return TRUE;
}
if(This->Private->pErrMsg) {
sqlite3_free(This->Private->pErrMsg);
This->Private->pErrMsg = NULL;
}
return FALSE;
}
//----------------------------------------------------------------------------
//关闭
static void SQLite_Close(struct _TSqlite *This)
{
if(This->Private->Active) {
sqlite3_free_table(This->Private->pData);
This->Private->pData = NULL;
free(This->Fields);
This->Private->Active = FALSE;
}
}
//----------------------------------------------------------------------------
// 返回记录数量
static int SQLite_RecordCount(struct _TSqlite *This)
{
return This->Private->RecordCount;
}
//----------------------------------------------------------------------------
// 返回表是否打开
static BOOL SQLite_Active(struct _TSqlite *This)
{
return This->Private->Active;
}
//----------------------------------------------------------------------------
// 返回字段数量
static int SQLite_FieldCount(struct _TSqlite *This)
{
return This->Private->FieldCount;
}
//----------------------------------------------------------------------------
/* 取得最后插入影响的ID. */
static int SQLite_LastRowId(struct _TSqlite *This)
{
return (int)sqlite3_last_insert_rowid(This->Private->db);
}
//----------------------------------------------------------------------------
//跳到记录号
static void SQLite_SetRecNo(struct _TSqlite *This,int RecNo)
{
if(RecNo>0 && RecNo<=This->Private->RecordCount)
This->Private->RecNo = RecNo;
}
//----------------------------------------------------------------------------
//首记录
static void SQLite_First(struct _TSqlite *This)
{
if(This->Private->pData)
This->Private->RecNo = 1;
else
This->Private->RecNo = 0;
}
//----------------------------------------------------------------------------
//末记录
static void SQLite_Last(struct _TSqlite *This)
{
if(This->Private->pData)
This->Private->RecNo = This->Private->RecordCount;
else
This->Private->RecNo = 0;
}
//----------------------------------------------------------------------------
//上一记录
static void SQLite_Prior(struct _TSqlite *This)
{
if(This->Private->pData) {
if(This->Private->RecNo>1)
This->Private->RecNo--;
}
}
//----------------------------------------------------------------------------
//下一记录
static void SQLite_Next(struct _TSqlite *This)
{
if(This->Private->pData) {
if(This->Private->RecNo<This->Private->RecordCount)
This->Private->RecNo++;
}
}
//----------------------------------------------------------------------------
//返回记录号
static int SQLite_RecNo(struct _TSqlite *This)
{
return This->Private->RecNo;
}
//----------------------------------------------------------------------------
//返回字段
static PSQLiteField SQLite_FieldByName(struct _TSqlite *This,char *Name)
{
int i;
char FieldName[SQL_NAME_MAX];
if(!This->Private->Active)
return NULL;
strupper(FieldName,Name,SQL_NAME_MAX);
for(i=0;i<This->Private->FieldCount;i++) {
if(strcmp(FieldName,This->Fields[i].Name)==0)
return &This->Fields[i];
}
DPRINT("SQL '%s' [%s] is not found\n",This->Private->SqlText,Name);
return NULL;
}
//----------------------------------------------------------------------------
//取SQL命令行
static int SQLite_GetSQLText(struct _TSqlite *This,char *pBuf,int Size)
{
if(!This->Private->SqlText)
return FALSE;
strncpy(pBuf,This->Private->SqlText,Size);
return TRUE;
}
//----------------------------------------------------------------------------
//设置SQL命令行
static void SQLite_SetSQLText(struct _TSqlite *This,char *SqlCmd)
{
int TextLen = strlen(SqlCmd)+1;
if(This->Private->Active)
return;
This->Private->SqlText = (char *)realloc(This->Private->SqlText,TextLen);
strcpy(This->Private->SqlText,SqlCmd);
}
static void SQLite_prepare(struct _TSqlite *This,char *SqlCmd)
{
sqlite3_prepare(This->Private->db,
SqlCmd,strlen(SqlCmd),
&This->Private->ppStmt,NULL);
}
static void SQLite_bind_reset(struct _TSqlite *This)
{
sqlite3_reset(This->Private->ppStmt);
This->Private->bind_num = 1;
}
static void SQLite_bind_get_reset(struct _TSqlite *This)
{
// sqlite3_reset(This->Private->ppStmt);
This->Private->bind_num = 0;
}
static void SQLite_finalize(struct _TSqlite *This)
{
sqlite3_finalize(This->Private->ppStmt);
}
static int SQLite_step(struct _TSqlite *This)
{
return sqlite3_step(This->Private->ppStmt);
}
static void SQLite_bind_int(struct _TSqlite *This,int arg)
{
sqlite3_bind_int(This->Private->ppStmt,This->Private->bind_num,arg);
This->Private->bind_num++;
}
static void SQLite_bind_blob(struct _TSqlite *This,void *data,int size)
{
sqlite3_bind_blob(This->Private->ppStmt,This->Private->bind_num,data,size,NULL);
This->Private->bind_num++;
}
static void SQLite_bind_text(struct _TSqlite *This,char *text)
{
sqlite3_bind_text(This->Private->ppStmt,This->Private->bind_num,text,-1,SQLITE_STATIC);
This->Private->bind_num++;
}
static void SQLite_get_blob_data(struct _TSqlite *This,void *data)
{
if(data) {
const void *p;
p = sqlite3_column_blob(This->Private->ppStmt,This->Private->bind_num);
int size = sqlite3_column_bytes(This->Private->ppStmt,This->Private->bind_num);
memcpy(data,p,size);
}
This->Private->bind_num++;
}
static void SQLite_get_text_data(struct _TSqlite *This,char *data)
{
if (data){
const unsigned char *p;
int size = sqlite3_column_bytes(This->Private->ppStmt,This->Private->bind_num);
p = sqlite3_column_text(This->Private->ppStmt,This->Private->bind_num);
memcpy(data,p,size);
}
This->Private->bind_num++;
}
//----------------------------------------------------------------------------
TSqlite * CreateLocalQuery(const char *FileName)
{
int ret;
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
TSqlite * This = (TSqlite *)malloc(sizeof(TSqlite));
memset(This,0,sizeof(TSqlite));
This->Private = (struct SqlitePrivate*)malloc(sizeof(struct SqlitePrivate));
This->sql_lock = (struct Sqlite_mutex *)malloc(sizeof(struct Sqlite_mutex));
memset(This->Private,0,sizeof(struct SqlitePrivate));
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&This->sql_lock->mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
ret = sqlite3_open(FileName, &This->Private->db);
if(ret!=SQLITE_OK) {
DPRINT("open db err:%s\n",sqlite3_errmsg(This->Private->db));
sqlite3_close(This->Private->db);
free(This->Private);
free(This);
return NULL;
}
This->file_name = FileName;
This->Destroy = SQLite_Destroy;
This->Open = SQLite_Open;
This->ExecSQL = SQLite_ExecSQL;
This->Close = SQLite_Close;
This->First = SQLite_First;
This->Last = SQLite_Last;
This->Prior = SQLite_Prior;
This->Next = SQLite_Next;
This->SetRecNo = SQLite_SetRecNo;
This->RecNo = SQLite_RecNo;
This->FieldByName = SQLite_FieldByName;
This->GetSQLText = SQLite_GetSQLText;
This->SetSQLText = SQLite_SetSQLText;
This->Active = SQLite_Active;
This->RecordCount = SQLite_RecordCount;
This->FieldCount = SQLite_FieldCount;
This->LastRowId = SQLite_LastRowId;
This->prepare = SQLite_prepare;
This->bind_reset = SQLite_bind_reset;
This->get_reset = SQLite_bind_get_reset;
This->finalize = SQLite_finalize;
This->step = SQLite_step;
This->bind_int = SQLite_bind_int;
This->bind_text = SQLite_bind_text;
This->bind_blob = SQLite_bind_blob;
This->getBlobData = SQLite_get_blob_data;
This->getBindText = SQLite_get_text_data;
return This;
}
//----------------------------------------------------------------------------
BOOL LocalQueryOpen(TSqlite *Query,char *SqlStr)
{
SQL_LOCK();
Query->Close(Query);
Query->SetSQLText(Query,SqlStr);
BOOL ret = Query->Open(Query);
SQL_UNLOCK();
return ret;
}
//----------------------------------------------------------------------------
BOOL LocalQueryExec(TSqlite *Query,char *SqlStr)
{
SQL_LOCK();
Query->Close(Query);
Query->SetSQLText(Query,SqlStr);
BOOL ret = Query->ExecSQL(Query);
SQL_UNLOCK();
return ret;
}
//----------------------------------------------------------------------------
char* LocalQueryOfChar(TSqlite *Query,char *FieldName,char *cBuf,int Size)
{
PSQLiteField Field;
Field = Query->FieldByName(Query,FieldName);
if(Field==NULL)
{
return cBuf;
}
return Field->AsChar(Field,cBuf,Size);
}
//----------------------------------------------------------------------------
int LocalQueryOfInt(TSqlite *Query,char *FieldName)
{
PSQLiteField Field;
Field = Query->FieldByName(Query,FieldName);
if(Field==NULL)
{
return 0;
}
return Field->AsInt(Field);
}
//----------------------------------------------------------------------------
double LocalQueryOfFloat(TSqlite *Query,char *FieldName)
{
PSQLiteField Field;
Field = Query->FieldByName(Query,FieldName);
if(Field==NULL)
{
return 0;
}
return Field->AsFloat(Field);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief sqlLoad 加载数据库文件并判断是否成功,若不成功则恢复备份文件,重新加载
*
* @param sql 数据库文件
* @param file 数据库文件名
*/
/* ---------------------------------------------------------------------------*/
void LocalQueryLoad(TSqliteData *sql)
{
sql->sql = CreateLocalQuery(sql->file_name);
if (sql->sql) {
DPRINT("Open %s successfully\n",sql->file_name);
} else {
DPRINT("Err:%s open failed\n",sql->file_name);
char file_bak[32];
sprintf(file_bak,"%s_bak",sql->file_name);
if (fileexists(file_bak) == 1) {
recoverData(sql->file_name);
sql->sql = CreateLocalQuery(sql->file_name);
}
}
}
<file_sep>/src/wireless/remotefile.h
/*
* =============================================================================
*
* Filename: remotefile.h
*
* Description: UDP下载文件
*
* Version: 1.0
* Created: 2019-09-03 14:16:49
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _REMOTEFILE_H
#define _REMOTEFILE_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifndef FALSE
#define FALSE 0
#define TRUE 1
#define BOOL int
#endif
#include "my_update.h"
enum {
UPDATE_FAIL_REASON_CREATE,
UPDATE_FAIL_REASON_CONNECT,
UPDATE_FAIL_REASON_FILENAME,
UPDATE_FAIL_REASON_RECV,
UPDATE_FAIL_REASON_RECVSIZE,
UPDATE_FAIL_REASON_OPEN,
UPDATE_FAIL_REASON_RENAME,
UPDATE_FAIL_REASON_ABORT,
};
enum {
OPEN_READ=1,
OPEN_WRITE,
OPEN_READWRITE,
FILE_CREATE_ALWAYS=0x100,
FILE_CREATE_NEW=0x200,
FILE_OPEN_ALWAYS=0x300,
FILE_OPEN_EXISTING=0x400,
FILE_OPEN_MASK=0xFF00
};
//---------------------------------------------------------------------------
struct RemoteFilePrivate; //私有数据
typedef struct _TRemoteFile
{
struct RemoteFilePrivate * Private;
BOOL (*Download)(struct _TRemoteFile* This,unsigned int hWnd,const char *SrcFile,
const char *DstFile,int ExecuteMode,UpdateFunc callback); //下载文件
int (*Open)(struct _TRemoteFile* This,const char *FileName,int OpenMode); //返回文件长度,-1打开失败
int (*Read)(struct _TRemoteFile* This,void *Buffer,int Size);
BOOL (*Write)(struct _TRemoteFile* This,void *Buffer,int Size);
int (*Seek)(struct _TRemoteFile* This,int offset,int origin);
BOOL (*SetEnd)(struct _TRemoteFile* This);
int (*GetPos)(struct _TRemoteFile* This);
void (*Close)(struct _TRemoteFile* This);
void (*Destroy)(struct _TRemoteFile* This);
} TRemoteFile;
TRemoteFile * CreateRemoteFile(const char *IP,const char *TempFile);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/gui/screen.h
/*
* =============================================================================
*
* Filename: screen.h
*
* Description: 窗口链表
*
* Version: 1.0
* Created: 2019-04-20 15:09:14
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _SCREEN_H
#define _SCREEN_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include "commongdi.h"
enum {
MSG_ENABLE_WINDOW = MSG_USER + 100,
MSG_DISABLE_WINDOW,
MSG_FORM_SETTING_TIME_SET_TIME,
MSG_FORM_SETTING_TIME_GET_TIME,
};
typedef struct _Formclass {
HWND hWnd;
char Class[16];
struct _Formclass * next;
}FormClass;
typedef struct _ScreenForm {
HWND hMainWnd; //主窗口 HWND hUpdate;
int Width;
int Height;
int Count; //合计数
FormClass * head,*tail; //窗口链表头与尾
FormClass *current; //窗口链表头与尾
BOOL (*Add)(HWND hWnd,const char *Class); //添加窗口
BOOL (*Del)(HWND hWnd); //删除窗口
HWND (*Find)(const char *Class); //查找窗口
void (*setCurrent)(const char *Class); //设置当前窗口
HWND (*getCurrent)(void); //拿到当前窗口
void (*ReturnMain)(void); //返回主窗口
void (*foreachForm)(int iMsg, WPARAM wParam, LPARAM lParam); //遍历所有窗口发送消息
} ScreenForm;
void screenInit(void);
extern ScreenForm Screen;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/module/updater/display/display.cpp
#include "display.h"
typedef unsigned short uint16_t;
typedef unsigned char uint8_t;
unsigned int RKDisplay::conv24to16(uint8_t r, uint8_t g, uint8_t b)
{
return ((((r >> 3) & 0x1F) << 11) | (((g >> 2) & 0x2F) << 5) | ((b >> 3) & 0x1F));
}
unsigned int RKDisplay::convColor(unsigned int color)
{
if (fbinfo.vinfo.bits_per_pixel == 16)
return ((color >> 3) & 0x1F) | (((color >> 10) & 0x3F) << 5) | (((color >> 19) & 0x1F) << 11);
return color;
}
void RKDisplay::RKDispClean()
{
if ((long)(fbinfo.mem_va) != -1) {
memset(fbinfo.mem_va, 0, fbinfo.size);
}
}
void RKDisplay::DrawPoint(int x, int y, unsigned int color)
{
int offset;
int bytes;
bytes = fbinfo.vinfo.bits_per_pixel >> 3;
offset = x * bytes + y * fbinfo.vinfo.xres * bytes;
if (fbinfo.vinfo.bits_per_pixel == 16) {
*(fbinfo.mem_va + offset) = color & 0xff;
*(fbinfo.mem_va + offset + 1) = (color >> 8) & 0xff;
} else {
*(fbinfo.mem_va + offset) = color & 0xff;
*(fbinfo.mem_va + offset + 1) = (color >> 8) & 0xff;
*(fbinfo.mem_va + offset + 2) = (color >> 16) & 0xff;
*(fbinfo.mem_va + offset + 3) = 0;
}
}
void RKDisplay::DrawLine(struct disp_line line, bool shadow)
{
for (int j = line.y1; j <= line.y2; j++) {
if (shadow) {
unsigned char b = 255 * j / (fbinfo.vinfo.xres - 10);
unsigned char g = 255;
unsigned char r = 255;
line.color = conv24to16(r, g, b);
}
for (int i = line.x1; i <= line.x2; i++)
DrawPoint(i, j, line.color);
}
}
void RKDisplay::DrawRect(struct disp_rect rect, bool fill, bool shadow)
{
struct disp_line line_top;
struct disp_line line_bottom;
struct disp_line line_left;
struct disp_line line_right;
line_top.x1 = rect.x;
line_top.x2 = rect.x + rect.w;
line_top.y2 = line_top.y1 = rect.y;
line_top.color = rect.color;
line_bottom.x1 = rect.x;
line_bottom.x2 = rect.x + rect.w;
line_bottom.y2 = line_bottom.y1 = rect.y + rect.h;
line_bottom.color = rect.color;
line_left.x1 = line_left.x2 = rect.x;
line_left.y1 = rect.y;
line_left.y2 = rect.y + rect.h;
line_left.color = rect.color;
line_right.x1 = line_right.x2 = rect.x + rect.w;
line_right.y1 = rect.y;
line_right.y2 = rect.y + rect.h;
line_right.color = rect.color;
if (fill) {
line_left.y2--;
for (int i = rect.x; i <= (rect.w + rect.x); i++) {
line_left.x1 = line_left.x2 = i;
DrawLine(line_left, shadow);
}
} else {
DrawLine(line_top);
DrawLine(line_bottom);
DrawLine(line_left);
DrawLine(line_right);
}
usleep(10 * 1000);
}
void RKDisplay::DrawEnChar(int x, int y, unsigned char *codes, int color)
{
int i = 0;
for (i = 0; i < 16; ++ i) {
int j = 0;
x += 8;
for (j = 0; j < 8; ++j) {
--x;
if ((codes[i] >> j) & 0x1)
DrawPoint(x , y, color);
}
++y;
}
}
void RKDisplay::DrawCnChar(int x, int y, unsigned char *codes, int color)
{
}
void RKDisplay::DrawString(struct disp_cap cap)
{
int pos = 0;
int x = cap.x;
int y = cap.y;
unsigned char *ptr;
unsigned int ch;
unsigned int cl;
unsigned int offset;
while (*(cap.str + pos)) {
ch = (unsigned int)cap.str[pos];
cl = (unsigned int)cap.str[pos + 1];
if (( ch >= 0xa1) && (ch < 0xf8) && (cl >= 0xa1) && (cl < 0xff)) {
offset = ((ch - 0xa1) * 94 + (cl - 0xal)) * 32;
ptr = __ASCII8X16__ + offset;
//DrawCnChar(x, y, ptr, cap.color);
x += 16;
pos += 2;
} else {
ptr = __ASCII8X16__ + 16 * ch;
DrawEnChar(x, y + 4, ptr, cap.color);
x += 8;
pos += 1;
}
}
}
RKDisplay::RKDisplay()
{
fbinfo.fd = open("/dev/fb0", O_RDWR);
if (!fbinfo.fd) {
printf("Error: cannot open framebuffer device.\n");
return;
}
/* Get fixed fi information */
if (ioctl(fbinfo.fd, FBIOGET_FSCREENINFO, &fbinfo.finfo)) {
printf("Error reading fixed information.\n");
return;
}
/* Get variable fi information */
if (ioctl(fbinfo.fd, FBIOGET_VSCREENINFO, &fbinfo.vinfo)) {
printf("Error reading variable information.\n");
return;
}
/* Figure out the size of */
fbinfo.size = fbinfo.vinfo.xres * fbinfo.vinfo.yres * fbinfo.vinfo.bits_per_pixel / 8;
/* Map the device to memory */
fbinfo.mem_va = (char *)mmap(0, fbinfo.size,
PROT_READ | PROT_WRITE, MAP_SHARED, fbinfo.fd, 0);
if ((long)(fbinfo.mem_va) == -1) {
printf("Error: failed to map framebuffer device to memory.\n");
return;
}
}
RKDisplay::~RKDisplay()
{
munmap(fbinfo.mem_va, fbinfo.size);
close(fbinfo.fd);
fbinfo.fd = -1;
}
#if 0
int main(int argc, char const *argv[])
{
int pos = 0;
RKDisplay* RKdisp = new RKDisplay();
struct disp_rect box_rect;
box_rect.x = 100;
box_rect.y = 270;
box_rect.w = 280;
box_rect.h = 60;
box_rect.color = RKdisp->convColor(0xFFFFFFFF);
struct disp_rect fill_rect;
fill_rect.x = box_rect.x;
fill_rect.y = box_rect.y;
fill_rect.w = box_rect.w / 10;
fill_rect.h = box_rect.h;
fill_rect.color = RKdisp->convColor(0xFFFFFFFF);
struct disp_cap cap;
memcpy(cap.str, "update kernel", sizeof("update kernel"));
cap.str_len = strlen(cap.str) * 8;
cap.x = (RKdisp->fbinfo.vinfo.xres - cap.str_len) >> 1;
cap.y = 200;
cap.color = 0xFFFFFFFF;
while (1) {
if (!(pos % 10)) {
RKdisp->RKDispClean();
RKdisp->DrawRect(box_rect);
RKdisp->DrawString(cap);
pos = 0;
}
fill_rect.x = box_rect.x + pos * fill_rect.w;
RKdisp->DrawRect(fill_rect, 1);
usleep(1000 * 1000);
pos++;
}
delete RKdisp;
RKdisp = NULL;
return 0;
}
#endif
<file_sep>/src/gui/form_videolayer.c
/*
* =============================================================================
*
* Filename: form_videolayer.c
*
* Description: 初始化主窗口
*
* Version: 1.0
* Created: 2019-04-19 16:47:01
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include "externfunc.h"
#include "debug.h"
#include "screen.h"
#include "config.h"
#include "protocol.h"
#include "sensor_detector.h"
#include "thread_helper.h"
#include "my_button.h"
#include "my_status.h"
#include "my_static.h"
#include "my_title.h"
#include "my_battery.h"
#include "my_scroll.h"
#include "my_video.h"
#include "form_video.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
extern void createFormMain(HWND hMainWnd,void (*callback)(void));
extern int createFormPowerOff(HWND hMainWnd);
extern int createFormPowerOffLowPower(void);
extern int createFormPowerOffCammerError(void);
extern int createFormPowerOffCammerErrorSleep(void);
extern int createFormUpdate(HWND hMainWnd);
extern int createFormTopmessage(HWND hMainWnd,char *title,char *content,void (*fConfirm)(void),void (*fCancel)(void));
extern void formMainLoadBmp(void);
extern void formSettingLoadBmp(void);
extern void formMonitorLoadBmp(void);
extern void formSettingWifiLoadBmp(void);
extern void formPasswordLoadBmp(void);
extern void formSettingLocalLoadBmp(void);
extern void formSettingStoreLoadBmp(void);
extern void formSettingQrcodeLoadBmp(void);
extern void formSettingUpdateLoadBmp(void);
extern void formSettingDoorbellLoadBmp(void);
extern void formSettingRingsLoadBmp(void);
extern void formSettingRingsVolumeLoadBmp(void);
extern void formSettingAlarmLoadBmp(void);
extern void formSettingPirStrengthLoadBmp(void);
extern void formSettingPirTimerLoadBmp(void);
extern void formSettingBrightnessLoadBmp(void);
extern void formSettingTimerLoadBmp(void);
extern void formSettingDateLoadBmp(void);
extern void formSettingTimeLoadBmp(void);
extern void formSettingMuteLoadBmp(void);
extern void formSettingTalkLoadBmp(void);
extern void formSettingCaptureVideoLoadBmp(void);
extern void formSettingFaceLoadBmp(void);
extern void formSettingScreenLoadBmp(void);
extern void formSettingSleepTimeLoadBmp(void);
extern void formSettingPowerLoadBmp(void);
extern void formVideoInitInterface(void);
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_MAIN > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
typedef void (*InitBmpFunc)(void) ;
typedef struct {
void (*init)(void);
MyControls ** controls;
}MyCtrls;
#define TIME_1S (100)
enum {
IDC_TIMER_1S , // 1s定时器
IDC_TIMER_NUM,
};
enum {
UI_FORMAT_BGRA_8888 = 0x1000,
UI_FORMAT_RGB_565,
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
PLOGFONT font36;
PLOGFONT font22;
PLOGFONT font20;
static MyCtrls ctrls[] = {
{initMyButton,&my_button},
{initMyStatus,&my_status},
{initMyStatic,&my_static},
{initMyTitle, &my_title},
{initMyBattery,&my_battery},
{initMyScroll,&my_scroll},
{NULL},
};
static FontLocation font_load[] = {
{&font36, 36,FONT_WEIGHT_DEMIBOLD},
{&font22, 22,FONT_WEIGHT_DEMIBOLD},
{&font20, 20,FONT_WEIGHT_DEMIBOLD},
{NULL}
};
static InitBmpFunc load_bmps_func[] = {
formMainLoadBmp,
formSettingLoadBmp,
formMonitorLoadBmp,
formSettingWifiLoadBmp,
formPasswordLoadBmp,
formSettingLocalLoadBmp,
formSettingStoreLoadBmp,
formSettingQrcodeLoadBmp,
formSettingUpdateLoadBmp,
formSettingDoorbellLoadBmp,
formSettingRingsLoadBmp,
formSettingRingsVolumeLoadBmp,
formSettingAlarmLoadBmp,
formSettingPirStrengthLoadBmp,
formSettingPirTimerLoadBmp,
formSettingBrightnessLoadBmp,
formSettingTimerLoadBmp,
formSettingDateLoadBmp,
formSettingTimeLoadBmp,
formSettingMuteLoadBmp,
formSettingTalkLoadBmp,
formSettingCaptureVideoLoadBmp,
formSettingFaceLoadBmp,
formSettingScreenLoadBmp,
formSettingSleepTimeLoadBmp,
formSettingPowerLoadBmp,
NULL,
};
static HWND hwnd_videolayer = HWND_INVALID;
static int flag_timer_stop = 0;
static int auto_close_lcd = 0;
static int sleep_timer = 0; // 进入睡眠倒计时
static int poweroff_timer = 0; // 进入关机倒计时
static int screen_on = 0;
static BmpLocation base_bmps[] = {
{NULL},
};
/* ---------------------------------------------------------------------------*/
/**
* @brief setAutoCloseLcdTime 设置关闭屏幕倒计时,同时重置睡眠倒计时
*
* @param count
*/
/* ---------------------------------------------------------------------------*/
static void setAutoCloseLcdTime(int count)
{
auto_close_lcd = count;
sleep_timer = 0;
}
void resetAutoSleepTimerLong(void)
{
sleep_timer = SLEEP_LONG_TIMER;
}
void resetAutoSleepTimerShort(void)
{
sleep_timer = g_config.sleep_time;
}
static void enableAutoClose(void)
{
Screen.setCurrent("TFrmVL");
flag_timer_stop = 0;
setAutoCloseLcdTime(g_config.screensaver_time);
my_video->showLocalVideo();
}
void screenAutoCloseStop(void)
{
setAutoCloseLcdTime(0);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formVideoLayerScreenOn 点亮屏幕
*/
/* ---------------------------------------------------------------------------*/
void formVideoLayerScreenOn(void)
{
screensaverSet(1);
setAutoCloseLcdTime(g_config.screensaver_time);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formVideoLayerScreenOff 关闭屏幕
*/
/* ---------------------------------------------------------------------------*/
void formVideoLayerScreenOff(void)
{
screensaverSet(0);
screenAutoCloseStop();
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formVideoLayerGotoPoweroff 关机时调用
*/
/* ---------------------------------------------------------------------------*/
void formVideoLayerGotoPoweroff(void)
{
my_video->hideVideo();
screensaverSet(1);
screenAutoCloseStop();
createFormPowerOff(0);
}
static void interfaceLowPowerToPowerOff(void)
{
my_video->hideVideo();
screensaverSet(1);
screenAutoCloseStop();
createFormPowerOffLowPower();
auto_close_lcd = 0;
poweroff_timer = POWEROFF_TIMER;
}
void cammerErrorToPowerOff(void)
{
my_video->hideVideo();
screensaverSet(1);
screenAutoCloseStop();
if (sensor->getEleState()) {
createFormPowerOffCammerErrorSleep();
} else {
createFormPowerOffCammerError();
poweroff_timer = POWEROFF_TIMER;
}
auto_close_lcd = 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formVideoLayerTimerProc1s 窗口相关定时函数
*
* @returns 1按键超时退出 0未超时退出
*/
/* ---------------------------------------------------------------------------*/
static void formVideoLayerTimerProc1s(HWND hwnd)
{
if (auto_close_lcd) {
// printf("auto_close_ld:%d\n",auto_close_lcd );
if (--auto_close_lcd == 0) {
screensaverSet(0);
if(sleep_timer < g_config.sleep_time)
sleep_timer = g_config.sleep_time;
}
}
if (poweroff_timer) {
printf("power:%d\n", poweroff_timer);
if (--poweroff_timer == 0)
protocol_singlechip->cmdPowerOff();
} else if (sleep_timer && auto_close_lcd == 0 && (sensor->getEleState() == 0)) {
printf("sleep:%d\n", sleep_timer);
if (--sleep_timer == 0)
protocol_hardcloud->enableSleepMpde();
}
}
static void * loadBmpsThread(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
int i;
for (i=0; load_bmps_func[i] != NULL; i++) {
load_bmps_func[i]();
}
return NULL;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formVideoLayerProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ---------------------------------------------------------------------------*/
static int formVideoLayerProc(HWND hWnd, int message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case MSG_CREATE:
{
screenInit();
auto_close_lcd = g_config.screensaver_time;
Screen.Add(hWnd,"TFrmVL");
hwnd_videolayer = hWnd;
bmpsLoad(base_bmps);
createThread(loadBmpsThread,"1");
fontsLoad(font_load);
SetTimer(hWnd, IDC_TIMER_1S, TIME_1S);
HWND form = createFormPowerOff(hWnd);
ShowWindow(form,SW_HIDE);
form = createFormUpdate(hWnd);
ShowWindow(form,SW_HIDE);
form = createFormTopmessage(hWnd,NULL,NULL,NULL,NULL);
ShowWindow(form,SW_HIDE);
form = createFormVideo(hWnd,FORM_VIDEO_TYPE_CAPTURE,NULL,0);
ShowWindow(form,SW_HIDE);
Screen.setCurrent("TFrmVL");
my_video->showLocalVideo();
formVideoInitInterface();
screensaverSet(1);
if (sensor) {
sensor->interface->uiLowPowerToPowerOff = interfaceLowPowerToPowerOff;
}
} break;
case MSG_ERASEBKGND:
drawBackground(hWnd,
(HDC)wParam,
0,NULL,0);
return 0;
case MSG_TIMER:
{
if (flag_timer_stop)
return 0;
if (wParam == IDC_TIMER_1S) {
formVideoLayerTimerProc1s(hWnd);
}
} return 0;
case MSG_LBUTTONUP:
{
if (screen_on) {
screen_on = 0;
break;
}
flag_timer_stop = 1;
setAutoCloseLcdTime(0);
createFormMain(hWnd,enableAutoClose);
} break;
case MSG_LBUTTONDOWN:
if (screensaverSet(1)) {
screen_on = 1;
}
setAutoCloseLcdTime(g_config.screensaver_time);
break;
case MSG_ENABLE_WINDOW:
enableAutoClose();
break;
case MSG_DISABLE_WINDOW:
flag_timer_stop = 1;
sleep_timer = 0;
break;
case MSG_DESTROY:
{
Screen.Del(hWnd);
DestroyAllControls (hWnd);
} return 0;
case MSG_CLOSE:
{
KillTimer (hWnd,IDC_TIMER_1S);
DestroyMainWindow (hWnd);
PostQuitMessage (hWnd);
} return 0;
default:
break;
}
return DefaultMainWinProc(hWnd, message, wParam, lParam);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formVideoLayerCreate 创建主窗口
*
* @param AppProc
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
void formVideoLayerCreate(void)
{
MAINWINCREATE CreateInfo;
int i;
for (i=0; ctrls[i].init != NULL; i++) {
ctrls[i].init();
(*ctrls[i].controls)->regist();
}
CreateInfo.dwStyle = WS_NONE;
CreateInfo.dwExStyle = WS_EX_NONE;//WS_EX_AUTOSECONDARYDC;
CreateInfo.spCaption = "cateye";
CreateInfo.hMenu = 0;
CreateInfo.hCursor = GetSystemCursor(IDC_ARROW);
CreateInfo.hIcon = 0;
CreateInfo.MainWindowProc = formVideoLayerProc;
CreateInfo.lx = 0;
CreateInfo.ty = 0;
CreateInfo.rx = SCR_WIDTH;
CreateInfo.by = SCR_HEIGHT;
CreateInfo.iBkColor = GetWindowElementColor(WE_MAINC_THREED_BODY);
CreateInfo.dwAddData = 0;
CreateInfo.dwReserved = 0;
CreateInfo.hHosting = HWND_DESKTOP;
CreateMainWindow (&CreateInfo);
if (hwnd_videolayer == HWND_INVALID)
return ;
ShowWindow(hwnd_videolayer, SW_SHOWNORMAL);
MSG Msg;
while (GetMessage(&Msg, hwnd_videolayer)) {
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
for (i=0; ctrls[i].init != NULL; i++) {
(*ctrls[i].controls)->unregist();
}
MainWindowThreadCleanup (hwnd_videolayer);
hwnd_videolayer = 0;
}
<file_sep>/module/updater/wget/httpd.h
#ifndef _HTTPD_GET_H_
#define _HTTPD_GET_H_
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <netdb.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/time.h>
#include "display.h"
enum {
URL_TYPE_UNKNOW = 0,
URL_TYPE_FIRMWARE,
URL_TYPE_KERNEL,
URL_TYPE_DTB,
URL_TYPE_USERDATA,
URL_TYPE_BOOT,
};
struct HTTP_RES_HEADER {
int status_code;
char content_type[128];
long content_length;
};
class Httpd
{
private:
void parse_url(const char *url, char *host, int *port, char *file_name);
struct HTTP_RES_HEADER parse_header(char *response);
void get_ip_addr(char *host_name, char *ip_addr);
unsigned long get_file_size(const char *filename);
void progress_bar(long cur_size, long total_size, double speed);
void download(int client_socket, char *file_name, long content_length);
char downpath[256];
char filepath[256 + 40];
RKDisplay* RKdisp;
public:
Httpd(RKDisplay *disp = NULL);
~Httpd();
int setDownPath(char* path);
int get(char *url);
struct disp_rect cap_rect;
struct disp_cap cap;
};
#endif
<file_sep>/module/singlechip/CMakeLists.txt
aux_source_directory(. SRCS)
add_definitions(
-DLINUX -DSUPPORT_ION -DENABLE_ASSERT -DDEBUG
)
add_executable(singlechip ${SRCS})
target_link_libraries(singlechip
pthread rt drivers hal
)
<file_sep>/src/wireless/my_dns.h
/*
* =============================================================================
*
* Filename: Dns.h
*
* Description: 域名解析
*
* Version: 1.0
* Created: 2016-06-27 15:29:35
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_DNS_H
#define _MY_DNS_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
int dnsGetIp(char *domain_name,char *ip);
// int dnsGetIp(char *domain_name,const char *ip);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/my_audio.h
/*
* =============================================================================
*
* Filename: my_audio.h
*
* Description: 播放相关音频文件
*
* Version: 1.0
* Created: 2019-06-27 13:26:32
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_AUDIO_H
#define _MY_AUDIO_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
void myAudioPlayRecognizer(char *usr_name);
void myAudioPlayRing(void);
void myAudioPlayRingOnce(void);
void myAudioStopPlay(void);
void myAudioPlayAlarm(void);
void myAudioPlayDindong(void);
int isNeedToPlay(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/drivers/jpeg_enc_dec.h
/*
* =============================================================================
*
* Filename: jpeg_enc_dec.h
*
* Description: jpeg编解码,jpeg9.0版本
*
* Version: 1.0
* Created: 2019-06-15 20:45:37
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _JPEG_ENC_DEC_H
#define _JPEG_ENC_DEC_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
void jpegIncDecInit(void);
int jpegToYuv420sp(unsigned char* jpeg_buffer,
int jpeg_size,
int *out_width, int *out_height,
unsigned char** yuv_buffer, int* yuv_size );
int yuv420spToJpeg(unsigned char* yuv_buffer, int width, int height,
unsigned char** jpeg_buffer, int* jpeg_size);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/drivers/mp4_muxer/mp4_muxer.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "mp4v2/mp4v2.h"
#include "faac.h"
#include "externfunc.h"
typedef struct _MP4ENC_NaluUnit
{
int type;
int size;
unsigned char *data;
}MP4ENC_NaluUnit;
typedef struct _MP4ENC_INFO {
unsigned int u32FrameRate;
unsigned int u32Width;
unsigned int u32Height;
unsigned int u32Profile;
}MP4ENC_INFO;
typedef struct _MuxerQueue {
uint8_t *buffer; // 队列内容
uint32_t cur_leng; // 当前队列长度
uint32_t total_leng; // 队列长度
uint32_t index_read; // 读下标
uint32_t index_write; // 写下标
}MuxerQueue;
static MP4ENC_INFO enc_info;
static MP4FileHandle mp4_fd = NULL;
static MP4TrackId video = MP4_INVALID_TRACK_ID;
static MP4TrackId audio = MP4_INVALID_TRACK_ID;
static faacEncHandle faac_fd = NULL;
static unsigned long inputSample = 0; //输入样本大小,在打开编码器时会得到此值
static unsigned long maxOutputBytes = 0; //最大输出,编码后的输出数据大小不会高于这个值,也是打开编码器时获得
static unsigned int mPCMBitSize = 16; //pcm位深,用于计算一帧pcm大小
static MuxerQueue muxer_queue;
static int mPCMBufferSize = 0; //一帧PCM缓存大小
static int mCountSize = 0; //计算缓存大小
static unsigned char* aacData = NULL ;
static unsigned char* pcm_buffer = NULL ;
static unsigned int pcm_data_buffer_leng ;
static uint64_t video_start_tick = 0;
static int video_frame_cnt = 0;
static int audio_sample = 0;
static int muxerQueueInit(int size)
{
memset(&muxer_queue,0,sizeof(muxer_queue));
muxer_queue.buffer = (uint8_t *)calloc(1,size);
muxer_queue.total_leng = size;
}
static int muxerQueueUninit(void)
{
if (muxer_queue.buffer)
free(muxer_queue.buffer);
}
static int muxerQueueWrite(uint8_t * data,uint32_t size)
{
if (size == 0)
return 0;
if (muxer_queue.cur_leng + size > muxer_queue.total_leng) {
printf("[%s]full!\n", __func__);
return 0;
}
muxer_queue.cur_leng += size;
if (muxer_queue.index_write + size > muxer_queue.total_leng) {
// 若写指针已经位于接近末尾位置,则分段拷贝数据,循环队列
int tail_leng = muxer_queue.total_leng - muxer_queue.index_write;
memcpy(&muxer_queue.buffer[muxer_queue.index_write],data,tail_leng) ;
int head_leng = size - tail_leng;
memcpy(&muxer_queue.buffer[0],&data[tail_leng],head_leng) ;
muxer_queue.index_write = head_leng;
} else {
memcpy(&muxer_queue.buffer[muxer_queue.index_write],data,size) ;
muxer_queue.index_write += size;
}
return 1;
}
static int muxerQueueRead(uint8_t * data,uint32_t size)
{
if (size == 0)
return 0;
if (muxer_queue.cur_leng < size) {
// printf("[%s]empty!\n", __func__);
return 0;
}
muxer_queue.cur_leng -= size;
if (muxer_queue.index_read + size > muxer_queue.total_leng) {
// 若读指针已经位于接近末尾位置,则分段拷贝数据,循环队列
int tail_leng = muxer_queue.total_leng - muxer_queue.index_read;
memcpy(data,&muxer_queue.buffer[muxer_queue.index_read],tail_leng) ;
int head_leng = size - tail_leng;
memcpy(&data[tail_leng],&muxer_queue.buffer[0],head_leng) ;
muxer_queue.index_read = head_leng;
} else {
memcpy(data,&muxer_queue.buffer[muxer_queue.index_read],size) ;
muxer_queue.index_read += size;
}
return 1;
}
static int muxerQueueGetCurLeng(void)
{
return muxer_queue.cur_leng;
}
static int32_t readH264Nalu(uint8_t *pPack, uint32_t nPackLen, unsigned int offSet, MP4ENC_NaluUnit *pNaluUnit)
{
unsigned int i = offSet;
while (i < nPackLen)
{
if (pPack[i++] == 0x00 && pPack[i++] == 0x00 && pPack[i++] == 0x01)// 开始码
{
unsigned int pos = i;
while (pos < nPackLen)
{
if (pPack[pos++] == 0x00 && pPack[pos++] == 0x00 && pPack[pos++] == 0x01)
break;
}
if (pos == nPackLen)
pNaluUnit->size = pos - i;
else
pNaluUnit->size = (pos - 3) - i;
pNaluUnit->type = pPack[i] & 0x1f;
pNaluUnit->data = (unsigned char *)&pPack[i];
return (pNaluUnit->size + i - offSet);
}
}
return 0;
}
static int32_t mp4v2VideoWrite(MP4FileHandle hFile, MP4TrackId *pTrackId,uint8_t *pPack,uint32_t nPackLen, MP4ENC_INFO *stMp4Info)
{
MP4ENC_NaluUnit stNaluUnit;
memset(&stNaluUnit, 0, sizeof(stNaluUnit));
int nPos = 0, nLen = 0;
while ((nLen = readH264Nalu(pPack, nPackLen, nPos, &stNaluUnit)) != 0)
{
switch (stNaluUnit.type)
{
case 7:
if (*pTrackId == MP4_INVALID_TRACK_ID)
{
video_start_tick = MyGetTickCount();
*pTrackId = MP4AddH264VideoTrack(hFile,
90000,
90000 / stMp4Info->u32FrameRate,
stMp4Info->u32Width,
stMp4Info->u32Height,
stNaluUnit.data[1], stNaluUnit.data[2], stNaluUnit.data[3], 3);
if (*pTrackId == MP4_INVALID_TRACK_ID) {
return 0;
}
MP4SetVideoProfileLevel(hFile, stMp4Info->u32Profile);
MP4AddH264SequenceParameterSet(hFile,*pTrackId,stNaluUnit.data,stNaluUnit.size);
}
break;
case 8:
if (*pTrackId == MP4_INVALID_TRACK_ID)
{
break;
}
MP4AddH264PictureParameterSet(hFile,*pTrackId,stNaluUnit.data,stNaluUnit.size);
break;
case 5:
case 1:
{
if (*pTrackId == MP4_INVALID_TRACK_ID)
{
break;
}
int nDataLen = stNaluUnit.size + 4;
unsigned char *data = (unsigned char *)malloc(nDataLen);
data[0] = stNaluUnit.size >> 24;
data[1] = stNaluUnit.size >> 16;
data[2] = stNaluUnit.size >> 8;
data[3] = stNaluUnit.size & 0xff;
memcpy(data + 4, stNaluUnit.data, stNaluUnit.size);
video_frame_cnt++;
uint64_t dur = MP4_INVALID_DURATION;
uint64_t diff_time = MyGetTickCount() - video_start_tick;
if (diff_time) {
float dwFrameRate = video_frame_cnt * 1000.0 / (float)diff_time;
dur = 90000 / dwFrameRate;
}
if (!MP4WriteSample(hFile, *pTrackId, data, nDataLen, dur, 0, stNaluUnit.type == 5?1:0))
{
free(data);
return 0;
}
free(data);
}
break;
default :
break;
}
nPos += nLen;
}
return 1;
}
int mp4MuxerAudioInit(int channels, long sample, int bits)
{
if (!mp4_fd)
return -1;
unsigned char *pp = NULL;
unsigned long pp_leng = 0;
int mPCMBitSize = 16;
audio_sample = sample;
faac_fd = faacEncOpen(sample,channels,&inputSample, &maxOutputBytes);
faacEncConfigurationPtr faac_cfg = faacEncGetCurrentConfiguration(faac_fd);
faac_cfg->inputFormat = FAAC_INPUT_16BIT;
faac_cfg->outputFormat = 0; /*0 - raw; 1 - ADTS*/
faac_cfg->bitRate = sample; //库内部默认为64000
faac_cfg->useTns = 0;
faac_cfg->allowMidside = 0;
faac_cfg->shortctl = SHORTCTL_NORMAL;
faac_cfg->aacObjectType = LOW;
faac_cfg->mpegVersion = MPEG4;//MPEG2
faacEncSetConfiguration(faac_fd,faac_cfg);
faacEncGetDecoderSpecificInfo(faac_fd,&pp,&pp_leng);
mPCMBufferSize = inputSample * mPCMBitSize / 8;
aacData = (unsigned char *)malloc(maxOutputBytes); //编码后输出数据(也就是AAC数据)存放位置
pcm_buffer = (unsigned char *)malloc(mPCMBufferSize); //编码后输出数据(也就是AAC数据)存放位置
muxerQueueInit(1024 *10);
audio = MP4AddAudioTrack(mp4_fd,sample,1024,MP4_MPEG4_AUDIO_TYPE);
MP4SetAudioProfileLevel(mp4_fd,2);
MP4SetTrackESConfiguration(mp4_fd, audio, pp, pp_leng);
return 0;
}
int mp4MuxerInit(int width,int height,char *file_name)
{
char *p[4] = {"isom","iso2","avc1","mp41"};
mp4_fd = MP4CreateEx(file_name,
0,1,1,"isom",0x00000200, p, 4);
enc_info.u32Width = width;
enc_info.u32Height = height;
enc_info.u32FrameRate = 15;
enc_info.u32Profile = 0x01;
video_start_tick = 0;
video_frame_cnt = 0;
return 0;
}
int mp4MuxerAppendVideo(uint8_t* data, int size)
{
if (!mp4_fd)
return -1;
mp4v2VideoWrite(mp4_fd,&video,data,size,&enc_info);
return 0;
}
int mp4MuxerAppendAudio(uint8_t* data, int size_in)
{
if (!mp4_fd)
return -1;
muxerQueueWrite(data,size_in);
if (muxerQueueGetCurLeng() < mPCMBufferSize)
return 0;
while (muxerQueueRead(pcm_buffer,mPCMBufferSize) != 0) {
int ret = faacEncEncode(
faac_fd, (int*) pcm_buffer, mPCMBufferSize / 2, aacData, maxOutputBytes);
if (ret > 0)
MP4WriteSample(mp4_fd, audio, aacData, ret, MP4_INVALID_DURATION, 0, 1);
}
return 1;
}
int mp4MuxerStop(void)
{
if (aacData)
free(aacData);
aacData = NULL;
if (pcm_buffer)
free(pcm_buffer);
pcm_buffer = NULL;
if (faac_fd)
faacEncClose(faac_fd);
faac_fd = NULL;
if (mp4_fd)
MP4Close(mp4_fd, 0);
mp4_fd = NULL;
video = MP4_INVALID_TRACK_ID;
audio = MP4_INVALID_TRACK_ID;
muxerQueueUninit();
video_start_tick = 0;
video_frame_cnt = 0;
return 0;
}
<file_sep>/src/drivers/queue.h
/*
* =============================================================================
*
* Filename: Queue.h
*
* Description: 队列
*
* Version: 1.0
* Created: 2016-08-16 09:16:52
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _QUEUE_H
#define _QUEUE_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
// #define LINUX_QUENE
#define MAX_COMMAND_QUEUE_SIZE 32
typedef enum QueueType {
QUEUE_NONBLOCK,
QUEUE_BLOCK,
}QueueType;
struct _QueuePriv;
typedef struct _Queue {
struct _QueuePriv *priv;
void (*post)(struct _Queue *,void *data);
int (*get)(struct _Queue *,void *data);
void (*setDataSize)(struct _Queue *,int size);
void (*destroy)(struct _Queue *This);
}Queue;
Queue * queueCreate(const char *queue_name,
QueueType type,
unsigned int Size);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/module/CMakeLists.txt
# 增加子目录,增加此目录
add_subdirectory(video)
add_subdirectory(singlechip)
add_subdirectory(cap)
add_subdirectory(stdioredirect)
add_subdirectory(updater)
<file_sep>/src/app/my_face.c
/*
* =============================================================================
*
* Filename: my_face.c
*
* Description: 人脸识别算法接口
*
* Version: 1.0
* Created: 2019-06-17 15:24:43
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "rdface/rd_face.h"
#include "my_face.h"
#include "config.h"
#include "debug.h"
#include "sql_handle.h"
#include "thread_helper.h"
#include "protocol.h"
#include "my_audio.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
extern const char *rdfaceGetFaceVersion(void);
extern const char *rdfaceGetDeviceKey(void);
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
MyFace *my_face;
static pthread_mutex_t mutex; // 初始化过程线程锁,初始化过程不可被打断
static int face_init_finished = 0; // 初始化是否结束,未结束时不处理其他功能
static int init(void)
{
if (g_config.face_enable == 0)
return 0;
// 不重复初始化
if (face_init_finished == 1)
return 1;
#ifdef USE_FACE
pthread_mutex_lock(&mutex);
face_init_finished = 0;
if(rdfaceInit() < 0) {
rdfaceUninit();
DPRINT("rdfaceInit error!");
pthread_mutex_unlock(&mutex);
return -1;
}
face_init_finished = 1;
pthread_mutex_unlock(&mutex);
#endif
return 1;
}
static int regist(MyFaceRegistData *data)
{
if (g_config.face_enable == 0)
return -1;
#ifdef USE_FACE
if (face_init_finished == 0)
goto regist_end;
pthread_mutex_lock(&mutex);
float *feature = NULL;
int feature_len = 0;
int ret = -1;
if (rdfaceRegist(data->image_buff,data->w,data->h,&feature,&feature_len) < 0 ){
DPRINT("regsit face err!\n");
goto regist_end;
}
ret = 0;
sqlInsertFace(data->id,data->nick_name,data->url,feature,feature_len);
regist_end:
if (feature)
free(feature);
pthread_mutex_unlock(&mutex);
return ret;
#endif
}
static int recognizerOnce(MyFaceRecognizer *data)
{
if (g_config.face_enable == 0)
return -1;
#ifdef USE_FACE
if (face_init_finished == 0)
return -1;
pthread_mutex_lock(&mutex);
int ret = rdfaceRecognizerOnce(data->image_buff,data->w,data->h,&data->age,&data->sex);
pthread_mutex_unlock(&mutex);
return ret;
#endif
}
static int deleteOne(char *id)
{
sqlDeleteFace(id);
return 0;
}
static int featureCompareCallback(float *feature,
void *face_data_out,
int sex,
int age)
{
#ifdef USE_FACE
MyFaceData data;
MyFaceData *p = (MyFaceData*)face_data_out;
float feature_src[512];
int result = -1;
if (sqlGetFaceCount()) {
sqlGetFaceStart();
while (1) {
memset(&data,0,sizeof(MyFaceData));
int ret = sqlGetFace(data.user_id,data.nick_name,data.url,feature_src);
if (ret == 0)
break;
float ret1 = rdfaceGetFeatureSimilarity(feature_src,feature);
if (ret1 > SIMILAYRITY) {
printf("similyrity:%f,:%s,name:%s,url:%s,sex:%d,age:%d\n",
ret1,data.user_id,data.nick_name,data.url,sex,age);
result = 0;
if (p)
memcpy(p,&data,sizeof(MyFaceData));
break;
}
};
sqlGetFaceEnd();
if (result == -1) {
if (p) {
p->age = age;
p->sex = sex;
}
result = 1;
}
} else {
if (p) {
p->age = age;
p->sex = sex;
}
result = 1;
}
return result;
#endif
}
static int recognizer(char *image_buff,int w,int h)
{
if (g_config.face_enable == 0)
return 0;
#ifdef USE_FACE
if (face_init_finished == 0)
return 0;
if (pthread_mutex_trylock(&mutex) != 0)
return 1;
MyFaceData face_data;
int ret = rdfaceRecognizer(image_buff,w,h,featureCompareCallback,&face_data);
if (ret == 0) {
printf("recognizer->id:%s,name:%s,url:%s\n",
face_data.user_id,face_data.nick_name,face_data.url);
if (protocol_singlechip)
protocol_singlechip->hasPeople(face_data.nick_name,face_data.user_id);
myAudioPlayRecognizer(face_data.nick_name);
} else if (ret == 1) {
printf("recognizer->age:%d,sex:%d\n",
face_data.age,face_data.sex);
}
pthread_mutex_unlock(&mutex);
#endif
return 1;
}
static void uninit(void)
{
if (face_init_finished == 0)
return;
#ifdef USE_FACE
pthread_mutex_lock(&mutex);
face_init_finished = 0;
rdfaceUninit();
pthread_mutex_unlock(&mutex);
#endif
printf("face uninited\n");
}
static const char *getVersion(void)
{
#ifdef USE_FACE
return rdfaceGetFaceVersion();
#else
return "未检测到人脸识别算法";
#endif
}
static const char *getDeviceKey(void)
{
#ifdef USE_FACE
return rdfaceGetDeviceKey();
#else
return "未检测到人脸识别算法";
#endif
}
void myFaceInit(void)
{
my_face = (MyFace *) calloc(1,sizeof(MyFace));
my_face->regist = regist;
my_face->recognizerOnce = recognizerOnce;
my_face->deleteOne = deleteOne;
my_face->recognizer = recognizer;
my_face->uninit = uninit;
my_face->init = init;
my_face->getVersion = getVersion;
my_face->getDeviceKey = getDeviceKey;
face_init_finished = 0;
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
}
<file_sep>/src/drivers/jpeg_enc_dec.c
/*
* =============================================================================
*
* Filename: jpeg_enc_dec.c
*
* Description: jpeg编解码
*
* Version: 1.0
* Created: 2019-06-15 20:45:18
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
#include <string.h>
#include "debug.h"
#include "jpeglib.h"
#include "turbojpeg.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
struct my_error_mgr {
struct jpeg_error_mgr pub; /* "public" fields */
jmp_buf setjmp_buffer; /* for return to caller */
};
typedef struct my_error_mgr * my_error_ptr;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*/
/**
* @brief yuv420spToYuv420p NV12转YUV420P
*
* @param yuv420sp
* @param yuv420p
* @param width
* @param height
* nv12(yuv420sp) 4x4 yuv420p 4x4
* YYYY YYYY
* YYYY YYYY
* YYYY YYYY
* YYYY YYYY
* UVUV UUUU
* UVUV VVVV
*/
/* ---------------------------------------------------------------------------*/
static void yuv420spToYuv420p(unsigned char* yuv420sp, unsigned char* yuv420p, int width, int height)
{
if (yuv420sp == NULL || yuv420p == NULL)
return;
int i, j;
int y_size = width * height;
unsigned char* y = yuv420sp;
unsigned char* uv = yuv420sp + y_size;
unsigned char* y_tmp = yuv420p;
unsigned char* u_tmp = yuv420p + y_size;
unsigned char* v_tmp = yuv420p + y_size * 5 / 4;
// y
memcpy(y_tmp, y, y_size);
// u
for (j = 0, i = 0; j < y_size/2; j+=2, i++) {
u_tmp[i] = uv[j];
v_tmp[i] = uv[j+1];
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief yuv420pToYuv420sp
*
* @param yuv420p
* @param yuv420sp
* @param width
* @param height
*
* nv12(yuv420sp) 4x4 yuv420p 4x4
* YYYY YYYY
* YYYY YYYY
* YYYY YYYY
* YYYY YYYY
* UVUV UUUU
* UVUV VVVV
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int yuv420pToYuv420sp(unsigned char * yuv420p,unsigned char* yuv420sp,int width,int height)
{
if (yuv420sp == NULL || yuv420p == NULL)
return -1;
int y_size = width * height;
unsigned char* y = yuv420p;
unsigned char* u = yuv420p + y_size;
unsigned char* v = yuv420p + y_size * 5 / 4;
unsigned char* y_tmp = yuv420sp;
unsigned char* uv_tmp = yuv420sp + y_size;
//Y
memcpy(y_tmp, y, y_size);
int i;
for (i=0; i<y_size/2; i++) {
if(i%2 == 0) {
*uv_tmp=*u;
u++;
} else {
*uv_tmp=*v;
v++;
}
uv_tmp++;
}
printf("convert finish\n");
return 0;
}
/*
* Here's the routine that will replace the standard error_exit method:
*/
/* ---------------------------------------------------------------------------*/
/**
* @brief yuv420spToJpeg
*
* @param yuv_buffer
* @param width
* @param height
* @param jpeg_buffer
* @param jpeg_size
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
int yuv420spToJpeg(unsigned char* yuv_buffer, int width, int height,
unsigned char** jpeg_buffer, int* jpeg_size)
{
tjhandle handle = NULL;
unsigned char *yuv_buffer_420p;
int quality = 50; // 编码质量50(1-100)
int flags = 0;
int padding = 1; // 1或4均可,但不能是0
int need_size = 0;
int ret = -1;
if (!yuv_buffer)
goto encode_err;
int yuv_size = width * height * 3/2;
handle = tjInitCompress();
if (handle == NULL) {
goto encode_err;
}
need_size = tjBufSizeYUV2(width, padding, height,TJSAMP_420);
if (need_size != yuv_size) {
printf("we detect yuv size: %d, but you give: %d, check again.\n", need_size, yuv_size);
goto encode_end;
}
yuv_buffer_420p = (unsigned char *)calloc(width*height*3/2,1);
yuv420spToYuv420p(yuv_buffer,yuv_buffer_420p,width,height);
ret = tjCompressFromYUV(handle, yuv_buffer_420p, width, padding, height,
TJSAMP_420, jpeg_buffer, (unsigned long *)jpeg_size, quality, flags);
if (ret < 0) {
printf("compress to jpeg failed: %s\n", tjGetErrorStr());
}
encode_end:
tjDestroy(handle);
if(yuv_buffer_420p)
free(yuv_buffer_420p);
encode_err:
return ret;
}
int jpegToYuv420sp(unsigned char* jpeg_buffer,
int jpeg_size,
int *out_width, int *out_height,
unsigned char** yuv_buffer, int* yuv_size )
{
tjhandle handle = NULL;
int width, height, subsample, colorspace;
int flags = 0;
int padding = 1; // 1或4均可,但不能是0
int ret = -1;
if (!jpeg_buffer)
return -1;
handle = tjInitDecompress();
if (handle == NULL) {
printf("%s():%s\n",__func__,tjGetErrorStr() );
goto jpeg_to_yuv_end;
}
tjDecompressHeader3(handle, jpeg_buffer, jpeg_size, &width, &height, &subsample, &colorspace);
*out_width = width;
*out_height = height;
DPRINT("w: %d h: %d subsample: %d color: %d\n", width, height, subsample, colorspace);
if (width < 0 || width > 1280 || height < 0 ||height > 720) {
goto jpeg_to_yuv_end;
}
flags |= 0;
// 注:经测试,指定的yuv采样格式只对YUV缓冲区大小有影响,实际上还是按JPEG本身的YUV格式来转换的
*yuv_size = tjBufSizeYUV2(width, padding, height, subsample);
unsigned char *yuv_buffer_420p =(unsigned char *)malloc(*yuv_size);
if (yuv_buffer_420p == NULL) {
printf("malloc buffer for rgb failed.\n");
goto jpeg_to_yuv_end;
}
ret = tjDecompressToYUV2(handle, jpeg_buffer, jpeg_size, yuv_buffer_420p, width,
padding, height, flags);
if (ret < 0) {
printf("compress to jpeg failed: %s\n", tjGetErrorStr());
}
*yuv_buffer =(unsigned char *)malloc(*yuv_size);
yuv420pToYuv420sp(yuv_buffer_420p,*yuv_buffer,width,height);
free(yuv_buffer_420p);
jpeg_to_yuv_end:
tjDestroy(handle);
return ret;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief jpegIncDecInit 必须要在c函数中有调用,否则cpp中提示找不到
*/
/* ---------------------------------------------------------------------------*/
void jpegIncDecInit(void)
{
}
<file_sep>/src/app/sensor_detector.h
/*
* =============================================================================
*
* Filename: sensor_detector.h
*
* Description: 传感器检测
*
* Version: virsion
* Created: 2019-07-06 15:48:08
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _SENSOR_DETECTOR_H
#define _SENSOR_DETECTOR_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef struct _SensorsInterface {
/* ---------------------------------------------------------------------------*/
/**
* @brief 更新UI电量
*
* @param
*/
/* ---------------------------------------------------------------------------*/
void (*uiUpadteElePower)(int power);
/* ---------------------------------------------------------------------------*/
/**
* @brief 更新UI充电状态
*
* @param
*/
/* ---------------------------------------------------------------------------*/
void (*uiUpadteEleState)(int state);
/* ---------------------------------------------------------------------------*/
/**
* @brief 电量为0时,提示电量过低,请充电的提示
*
* @param
*/
/* ---------------------------------------------------------------------------*/
void (*uiLowPowerToPowerOff)(void);
}SensorsInterface;
typedef struct _Sensors {
SensorsInterface *interface;
int (*getElePower)(void);
int (*getEleState)(void);
}Sensors;
extern Sensors *sensor;
void sensorDetectorInit(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/gui/form_setting_rings.c
/*
* =============================================================================
*
* Filename: form_setting_rings.c
*
* Description: 铃声设置界面
*
* Version: 1.0
* Created: 2018-03-01 23:32:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include "externfunc.h"
#include "screen.h"
#include "config.h"
#include "my_audio.h"
#include "my_button.h"
#include "my_title.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formSettingRingsProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void buttonExitPress(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonLeftPress(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonRightPress(HWND hwnd, int id, int nc, DWORD add_data);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_SET_LOCAL > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define BMP_LOCAL_PATH "setting/"
enum {
IDC_TIMER_1S = IDC_FORM_SETTING_RINGS,
IDC_BUTTON_EXIT,
IDC_BUTTON_LEFT,
IDC_BUTTON_RIGHT,
IDC_STATIC_IMAGE,
IDC_STATIC_TEXT,
IDC_TITLE,
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static BITMAP bmp_bkg_setting; // 背景
static int bmp_load_finished = 0;
static int flag_timer_stop = 0;
static BmpLocation bmp_load[] = {
{&bmp_bkg_setting,BMP_LOCAL_PATH"bell_icon.png"},
{NULL},
};
static MY_CTRLDATA ChildCtrls [] = {
STATIC_IMAGE(432,220,160,160,IDC_STATIC_IMAGE,(DWORD)&bmp_bkg_setting),
STATIC_LB(434,330,160,30,IDC_STATIC_TEXT,"铃声1",&font20,0xffffff),
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
// WS_EX_AUTOSECONDARYDC,
WS_EX_NONE,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "FsetRings",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formSettingRingsProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
.auto_close_time_set = 30,
};
static MyCtrlButton ctrls_button[] = {
{IDC_BUTTON_LEFT, MYBUTTON_TYPE_TWO_STATE|MYBUTTON_TYPE_TEXT_NULL,"left",225, 249,buttonLeftPress},
{IDC_BUTTON_RIGHT, MYBUTTON_TYPE_TWO_STATE|MYBUTTON_TYPE_TEXT_NULL,"right",698,249,buttonRightPress},
{0},
};
static MyCtrlTitle ctrls_title[] = {
{
IDC_TITLE,
MYTITLE_LEFT_EXIT,
MYTITLE_RIGHT_NULL,
0,0,1024,40,
"铃声设置",
"",
0xffffff, 0x333333FF,
buttonExitPress,
},
{0},
};
static FormBase* form_base = NULL;
static void enableAutoClose(void)
{
Screen.setCurrent(form_base_priv.name);
flag_timer_stop = 0;
}
static void reloadRings(void)
{
char buf[16] = {0};
sprintf(buf,"铃声%d",g_config.ring_num + 1);
SendMessage(GetDlgItem(form_base->hDlg,IDC_STATIC_TEXT),MSG_SETTEXT,0,(LPARAM)buf);
if (g_config.ring_num == 0) {
SendMessage(GetDlgItem(form_base->hDlg,IDC_BUTTON_LEFT),MSG_ENABLE,0,0);
} else if (g_config.ring_num == (MAX_RINGS_NUM - 1)) {
SendMessage(GetDlgItem(form_base->hDlg,IDC_BUTTON_RIGHT),MSG_ENABLE,0,0);
} else {
SendMessage(GetDlgItem(form_base->hDlg,IDC_BUTTON_LEFT),MSG_ENABLE,1,0);
SendMessage(GetDlgItem(form_base->hDlg,IDC_BUTTON_RIGHT),MSG_ENABLE,1,0);
}
}
/* ----------------------------------------------------------------*/
/**
* @brief buttonLeftPress wifi设置
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ----------------------------------------------------------------*/
static void buttonLeftPress(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
if (g_config.ring_num > 0) {
g_config.ring_num--;
myAudioPlayRingOnce();
ConfigSavePublic();
}
reloadRings();
}
static void buttonRightPress(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
if (g_config.ring_num < (MAX_RINGS_NUM - 1)) {
g_config.ring_num++;
myAudioPlayRingOnce();
ConfigSavePublic();
}
reloadRings();
}
/* ----------------------------------------------------------------*/
/**
* @brief buttonExitPress 退出按钮
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ----------------------------------------------------------------*/
static void buttonExitPress(HWND hwnd, int id, int nc, DWORD add_data)
{
myAudioStopPlay();
ShowWindow(GetParent(hwnd),SW_HIDE);
}
void formSettingRingsLoadBmp(void)
{
if (bmp_load_finished == 1)
return;
printf("[%s]\n", __FUNCTION__);
bmpsLoad(bmp_load);
my_button->bmpsLoad(ctrls_button,BMP_LOCAL_PATH);
bmp_load_finished = 1;
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_title[i].idc != 0; i++) {
ctrls_title[i].font = font20;
createMyTitle(hDlg,&ctrls_title[i]);
}
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
createMyButton(hDlg,&ctrls_button[i]);
}
reloadRings();
}
/* ----------------------------------------------------------------*/
/**
* @brief formSettingRingsProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ----------------------------------------------------------------*/
static int formSettingRingsProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
switch(message) // 自定义消息
{
case MSG_TIMER:
{
if (flag_timer_stop)
return 0;
} break;
case MSG_ENABLE_WINDOW:
enableAutoClose();
break;
case MSG_DISABLE_WINDOW:
flag_timer_stop = 1;
break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormSettingRings(HWND hMainWnd,void (*callback)(void))
{
HWND Form = Screen.Find(form_base_priv.name);
if(Form) {
Screen.setCurrent(form_base_priv.name);
ShowWindow(Form,SW_SHOWNORMAL);
} else {
if (bmp_load_finished == 0) {
// topMessage(hMainWnd,TOPBOX_ICON_LOADING,NULL );
return 0;
}
form_base_priv.callBack = callback;
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
<file_sep>/module/video/CMakeLists.txt
set(MODULE_VIDEO
main.cpp
h264_enc_dec/md_mpi_enc_api.c
camera/md_camerahal.cpp
buffer/md_camerabuf.cpp
process/md_display_process.cpp
process/md_encoder_process.cpp
)
add_definitions(
-DLINUX -DSUPPORT_ION -DENABLE_ASSERT -DDEBUG
)
add_executable(cammer_video ${MODULE_VIDEO})
target_link_libraries(cammer_video
-Wl,--start-group
ion pthread adk cam_ia cam_engine_cifisp rkfb rkrga
easymedia mpp drivers
turbojpeg
yuv rt
-Wl,--end-group
)
<file_sep>/include/ucpaas/UCSService.h
/*
* Copyright (c) 2017 The UCPAAS project authors. All Rights Reserved.
*
*/
#ifndef __UCS_INCLUDE_UCSSERVICE_H__
#define __UCS_INCLUDE_UCSSERVICE_H__
#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */
#include "ucs_defines.h"
/************************************************************************/
/* UCS enum definition */
/************************************************************************/
/************************************************************************/
/* UCS struct definition */
/************************************************************************/
// UCS connect status callback
typedef void(*connect_event_cb_f)(int ev_reason);
// UCS dailing out failed
typedef void(*dial_failed_cb_f)(const char* callid, int reason);
// call alerting
typedef void(*on_alerting_cb_f)(const char* callid);
// new call incoming
typedef void(*on_incomingcall_cb_f)(const char* callid, int calltype,
const char* caller_uid, const char* caller_name,
const char* userdata);
// call answer
typedef void(*on_answer_cb_f)(const char* callid);
// call hangup
typedef void(*on_hangup_cb_f)(const char* callid, int reason);
// received dtmf
typedef void(*received_dtmf_cb_f)(int dtmf_code);
// network quality report between call session
typedef void(*network_state_report_cb_f)(int reason, const char* netstate);
// UCS through data received callback
typedef void(*transdata_received_cb_f)(const char* from_userId,
const char* callid,
const char* trans_data);
// UCS send through data result callback
typedef void(*transdata_send_result_cb_f)(int err_code);
// UCS invoke it to change video stream
typedef void(*set_video_framerate_cb_f)(unsigned int target_width, unsigned int target_height,
unsigned int frame_rate, unsigned int bitrate);
// UCS init external playout device with given parameters
// sample_rate -- playout audio sample rate, 16k
// bytes_per_sample -- bytes of per sample, always 2 bytes = 16bits
// num_of_channels -- number of playout channels, always = 1
typedef void(*init_playout_cb_f)(unsigned int sample_rate,
unsigned int bytes_per_sample,
unsigned int num_of_channels);
// UCS init external recording device with given parameters
// sample_rate -- recording audio sample rate, 16000
// bytes_per_sample -- bytes of per sample, always 2 bytes = 16bits
// num_of_channels -- number of recording channels, always = 1
typedef void(*init_recording_cb_f)(unsigned int sample_rate,
unsigned int bytes_per_sample,
unsigned int num_of_channels);
// UCS read recording 10ms pcm data from external audio device
// audio_data -- recording pcm data
// size -- want to read data len
typedef int(*read_recording_data_cb_f)(char * audio_data,
unsigned int size);
// UCS write playout 10ms pcm data to external audio device
// audio_data -- playout data for external audio device
// size -- playout data length
typedef int(*write_playout_data_cb_f)(const char* audio_data,
unsigned int size);
typedef struct UCS_cb_vtable_t
{
connect_event_cb_f connect_cb;
dial_failed_cb_f dial_failed_cb;
on_alerting_cb_f on_alerting_cb;
on_answer_cb_f on_answer_cb;
on_incomingcall_cb_f on_incomingcall_cb;
on_hangup_cb_f on_hangup_cb;
received_dtmf_cb_f received_dtmf_cb;
network_state_report_cb_f network_state_report_cb;
transdata_received_cb_f transdata_received_cb;
transdata_send_result_cb_f transdata_send_result_cb;
set_video_framerate_cb_f set_video_framerate_cb;
init_playout_cb_f init_playout_cb;
init_recording_cb_f init_recording_cb;
read_recording_data_cb_f read_data_cb;
write_playout_data_cb_f write_data_cb;
} UCS_cb_vtable_t;
#define UCS_MAX_GROUP_DIAL_CALLEE_NUM 6
typedef struct UCS_groupdial_param_t
{
char calleeUserId[UCS_MAX_GROUP_DIAL_CALLEE_NUM][UCS_MAX_USERID_STR_LEN];
int calleeNum;
} UCS_groupdial_param_t;
typedef struct UCS_vqecfg_t
{
unsigned char aec_enable;
unsigned char agc_enable;
unsigned char ns_enable;
} UCS_vqecfg_t;
/************************************************************************/
/* UCS API declare */
/************************************************************************/
/************************************************************
Function : UCS_RegisterCallbackVtable
Description : set UCSService callbacks
Input : token -- user login token
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_RegisterCallbackVtable(UCS_cb_vtable_t* vtable);
/************************************************************
Function : UCS_Init
Description : Init UCSService, invoked after UCS_RegisterCallbackVtable()
Input : none
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_Init();
/************************************************************
Function : UCS_Destory
Description : Destory UCSService
Input :
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_Destory();
/************************************************************
Function : UCS_GetVersion
Description : get UCS version
Input :
Output : version
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_GetVersion(char* version);
/************************************************************
Function : UCS_SetLogEnable
Description : enable/disable UCS logger
Input : enable -- enable/disable UCS logger
: logpath -- sdk log path, without file name. should like: "/mnt/mmc/"
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_SetLogEnable(int enable, const char* logpath);
/************************************************************
Function : UCS_ViERingPreviewEnable
Description : enable/disable UCS video call ring preview
Input : enable -- 1: enable, 0: disable
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/7/19
************************************************************/
int UCS_ViERingPreviewEnable(int enable);
/************************************************************
Function : UCS_Connect
Description : connect to UCPAAS server
Input : token -- user login token
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_Connect(const char* token);
/************************************************************
Function : UCS_DisConnect
Description : disconnect connection with UCPAAS server
Input : none
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_DisConnect();
/************************************************************
Function : UCS_SendTransData
Description : Do through data sending
Input : isOffline - 1: use offline push, 0: use normal tcp trans
targetId -- target for send data to
transData -- through data
dataLen -- len of through data
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_SendTransData(const int isOffline, const char* targetId,
const char* transData, const int dataLen);
/************************************************************
Function : UCS_Dial()
Description : Do call outgoing
Input : callId -- called userid
: videoCall -- video call
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_Dial(const char* calledId, eUcsCallType callType);
/************************************************************
Function : UCS_GroupDial
Description : Do group call outgoing
Input : dialParam -- called info
: videoCall -- video call
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_GroupDial(UCS_groupdial_param_t* dialParam, eUcsCallType callType);
/************************************************************
Function : UCS_CallAnswer
Description : accept the incoming call
Input : none
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_CallAnswer();
/************************************************************
Function : UCS_CallHangUp
Description : hangup/reject the call
Input : none
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_CallHangUp();
/************************************************************
Function : UCS_SetExtAudioTransEnable
Description : enable/disable external audio pcm stream
Input : enable -- 1 for enable, 0 disable
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_SetExtAudioTransEnable(int enable);
/************************************************************
Function : UCS_SetExtVideoStreamEnable
Description : enable/disable external video h.264 stream
Input : enable -- 1 for enable, 0 disable
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_SetExtVideoStreamEnable(int enable);
/************************************************************
Function : UCS_SetVqeCfg
Description : Enable/disable media engine voice quality enhancement
Input : vqecfg -- voice quality enhancement config
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/8/21
************************************************************/
int UCS_SetVqeCfg(UCS_vqecfg_t* vqecfg);
/************************************************************
Function : UCS_PushExternalVideoStream
Description : push external h264 stream to UCS for sending out
Input : frameData -- h264 frame data
dataLen -- len of h264 frame data
Output : none
Return : 0 if succeed, else -1;
Remark : None
Modified : 2017/6/9
************************************************************/
int UCS_PushExternalVideoStream(const unsigned char* frameData, const unsigned int dataLen);
int UCS_get_video_frame(char *data, unsigned int* length, long long* timeStamp, int *frameType);
void UCS_video_start(int send_receive);
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */
#endif /* __UCS_INCLUDE_UCSSERVICE_H__ */
<file_sep>/module/updater/display/display.h
#ifndef _RK_DISPLAY_H_
#define _RK_DISPLAY_H_
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <pthread.h>
#include "font_bitmap.h"
struct disp_rect {
int x;
int y;
int w;
int h;
unsigned int color;
};
struct disp_line {
int x1;
int y1;
int x2;
int y2;
unsigned int color;
};
struct disp_cap {
int x;
int y;
int str_len;
char str[40];
unsigned int color;
};
struct fb_info {
struct fb_var_screeninfo vinfo;
struct fb_fix_screeninfo finfo;
int fd;
char *mem_va;
unsigned size;
};
class RKDisplay
{
private:
public:
RKDisplay();
~RKDisplay();
unsigned int conv24to16(uint8_t r, uint8_t g, uint8_t b);
unsigned int convColor(unsigned int color);
void RKDispClean();
void Draw(int length);
void DrawPoint(int x, int y, unsigned int color);
void DrawLine(struct disp_line line, bool shadow = 0);
void DrawRect(struct disp_rect rect, bool fill = 0, bool shadow = 0);
void DrawEnChar(int x, int y, unsigned char *codes, int color);
void DrawCnChar(int x, int y, unsigned char *codes, int color);
void DrawString(struct disp_cap cap);
struct fb_info fbinfo;
};
#endif
<file_sep>/src/gui/my_controls/my_battery.c
/*
* =====================================================================================
*
* Filename: MyBattery.c
*
* Description: 自定义电池图标
*
* Version: 1.0
* Created: 2015-12-09 16:22:37
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
/* ----------------------------------------------------------------*
* include head files
*-----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include "my_battery.h"
#include "debug.h"
#include "cliprect.h"
#include "internals.h"
#include "ctrlclass.h"
/* ----------------------------------------------------------------*
* extern variables declare
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*
* internal functions declare
*-----------------------------------------------------------------*/
static int myBatteryControlProc (HWND hwnd, int message, WPARAM wParam, LPARAM lParam);
/* ----------------------------------------------------------------*
* macro define
*-----------------------------------------------------------------*/
#define CTRL_NAME CTRL_MYBATTERY
/* ----------------------------------------------------------------*
* variables define
*-----------------------------------------------------------------*/
MyControls *my_battery;
static BITMAP image_charging;// 关闭状态图片
static BITMAP image_normal; // 打开状态图片
static BmpLocation base_bmps[] = {
{&image_charging,"setting/ico_Battery_c.png"},
{&image_normal, "setting/ico_Battery_nor.png"},
{NULL},
};
/* ---------------------------------------------------------------------------*/
/**
* @brief myBatteryRegist 注册控件
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static BOOL myBatteryRegist (void)
{
WNDCLASS WndClass;
WndClass.spClassName = CTRL_NAME;
WndClass.dwStyle = WS_NONE;
WndClass.dwExStyle = WS_EX_NONE;
WndClass.hCursor = GetSystemCursor (IDC_ARROW);
WndClass.iBkColor = 0;
WndClass.WinProc = myBatteryControlProc;
return RegisterWindowClass(&WndClass);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myBatteryCleanUp 卸载控件
*/
/* ---------------------------------------------------------------------------*/
static void myBatteryCleanUp (void)
{
UnregisterWindowClass(CTRL_NAME);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief paint 主要绘图函数
*
* @param hWnd
* @param hdc
*/
/* ---------------------------------------------------------------------------*/
static void paint(HWND hWnd,HDC hdc)
{
#define FILL_BMP_STRUCT(rc,img) rc.left, rc.top,img->bmWidth,img->bmHeight,img
char power_lever[16] = {0};
RECT rc_bmp,rc_text;
PCONTROL pCtrl;
pCtrl = Control (hWnd);
GetClientRect (hWnd, &rc_text);
if (!pCtrl->dwAddData2)
return;
MyBatteryCtrlInfo* pInfo = (MyBatteryCtrlInfo*)(pCtrl->dwAddData2);
// 写标题
SetTextColor(hdc,0xffffff);
SetBkMode(hdc,BM_TRANSPARENT);
SelectFont (hdc, pInfo->font);
sprintf(power_lever,"%d%%",pInfo->ele_quantity);
DrawText (hdc,power_lever, -1, &rc_text,
DT_LEFT | DT_VCENTER | DT_WORDBREAK | DT_SINGLELINE);
SetBkMode(hdc,BM_OPAQUE);
if (pInfo->state == 0) {
// 正常状态
rc_bmp.left = 64;
rc_bmp.top = 13;
rc_bmp.right = rc_bmp.left + pInfo->ele_quantity * 34 / 100 ;
rc_bmp.bottom = rc_bmp.top + image_normal.bmHeight - 7;
FillBoxWithBitmap(hdc,60,10,image_normal.bmWidth,image_normal.bmHeight,&image_normal);
// 绘制电量
if (pInfo->ele_quantity <= 10) {
SetBrushColor (hdc, RGBA2Pixel (hdc, 0xFF, 0x00, 0x00, 0xFF));
} else if (pInfo->ele_quantity <= 20) {
SetBrushColor (hdc, RGBA2Pixel (hdc, 0xFF, 0x69, 0x00, 0xFF));
} else {
SetBrushColor (hdc, RGBA2Pixel (hdc, 0xFF, 0xFF, 0xFF, 0xFF));
}
FillBox (hdc, rc_bmp.left, rc_bmp.top, RECTW(rc_bmp),RECTH(rc_bmp));
// myFillBox(hdc,&rc_bmp,0xffffff);
} else {
// 充电状态
FillBoxWithBitmap(hdc,60,10,image_charging.bmWidth,image_charging.bmHeight,&image_charging);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myBatteryControlProc 控件主回调函数
*
* @param hwnd
* @param message
* @param wParam
* @param lParam
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int myBatteryControlProc (HWND hwnd, int message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PCONTROL pCtrl;
DWORD dwStyle;
MyBatteryCtrlInfo* pInfo;
pCtrl = Control (hwnd);
pInfo = (MyBatteryCtrlInfo*)pCtrl->dwAddData2;
dwStyle = GetWindowStyle (hwnd);
switch (message) {
case MSG_CREATE:
{
MyBatteryCtrlInfo* data = (MyBatteryCtrlInfo*)pCtrl->dwAddData;
pInfo = (MyBatteryCtrlInfo*) calloc (1, sizeof (MyBatteryCtrlInfo));
if (pInfo == NULL)
return -1;
memset(pInfo,0,sizeof(MyBatteryCtrlInfo));
pInfo->font = data->font;
pInfo->ele_quantity = data->ele_quantity;
pInfo->state = data->state;
pCtrl->dwAddData2 = (DWORD)pInfo;
return 0;
}
case MSG_DESTROY:
free(pInfo);
break;
case MSG_PAINT:
hdc = BeginPaint (hwnd);
paint(hwnd,hdc);
EndPaint (hwnd, hdc);
return 0;
case MSG_SET_QUANTITY:
pInfo->ele_quantity = wParam;
InvalidateRect (hwnd, NULL, TRUE);
break;
case MSG_SET_STATUS:
pInfo->state = wParam;
InvalidateRect (hwnd, NULL, TRUE);
break;
default:
break;
}
return DefaultControlProc (hwnd, message, wParam, lParam);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief bmpsMainTitleLoad 加载主界面图片
*
* @param controls
**/
/* ---------------------------------------------------------------------------*/
static void myBatteryBmpsLoad(void *ctrls,char *path)
{
bmpsLoad(base_bmps);
}
static void myBatteryBmpsRelease(void *ctrls)
{
}
/* ---------------------------------------------------------------------------*/
/**
* @brief createMyBattery 创建单个静态控件
*
* @param hWnd
* @param id
* @param x,y,w,h 坐标
* @param image_normal 正常图片
* @param image_press 按下图片
* @param display 是否显示 0不显示 1显示
* @param mode 是否为选择模式 0非选择 1选择
*/
/* ---------------------------------------------------------------------------*/
HWND createMyBattery(HWND hWnd,MyCtrlBattery *ctrl)
{
HWND hCtrl;
MyBatteryCtrlInfo pInfo;
pInfo.font = ctrl->font;
pInfo.ele_quantity = ctrl->ele_quantity;
pInfo.state = ctrl->state;
hCtrl = CreateWindowEx(CTRL_NAME,"",WS_VISIBLE|WS_CHILD,WS_EX_TRANSPARENT,
ctrl->idc,ctrl->x,ctrl->y,ctrl->w,ctrl->h, hWnd,(DWORD)&pInfo);
return hCtrl;
}
void initMyBattery(void)
{
my_battery = (MyControls *)malloc(sizeof(MyControls));
my_battery->regist = myBatteryRegist;
my_battery->unregist = myBatteryCleanUp;
my_battery->bmpsLoad = myBatteryBmpsLoad;
my_battery->bmpsRelease = myBatteryBmpsRelease;
my_battery->bmpsLoad(NULL,NULL);
}
<file_sep>/src/app/my_gpio.h
/*
* =====================================================================================
*
* Filename: MyGpioCtr.h
*
* Description: 创建GPIO对象
*
* Version: 1.0
* Created: 2015-12-24 09:26:29
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
#ifndef _MY_GPIO_H
#define _MY_GPIO_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define FLASH_FOREVER 0x7FFFFFFF
typedef enum {
ENUM_GPIO_MICKEY, // MIC: H外L内
ENUM_GPIO_SPKL, // SPK:机内 高开低关
ENUM_GPIO_SPKR, // SPK:机外 高开低关
ENUM_GPIO_KEYLED_BLUE, // 红灯 高开低关,LED1
ENUM_GPIO_KEYLED_RED, // 白灯 高开低关,LED2
ENUM_GPIO_IRLEDEN, // 红外灯 高开低关
ENUM_GPIO_ASNKEY, // 消回音 H外L内
ENUM_GPIO_MICEN, // 模拟电子开关电源使能脚 高关低开
ENUM_GPIO_SDCTRL, // TF卡2.0标准时拉高 TF卡3.0标准时拉低
ENUM_GPIO_ICRAIN, // 1. A高B低 为白天彩色模式
ENUM_GPIO_ICBAIN, // 2. A低B高为晚上黑白模式
}GPIO_TBL;
typedef enum {//50ms为周期
FLASH_STOP = 0,
FLASH_FAST = 4, //200ms
FLASH_SLOW = 20, //1s
}STRUCT_SPEED;
enum {
IO_NO_EXIST = -1, //当IO不存在时,用于个别型号不存在该IO口
IO_INPUT = 0, // 输入
IO_ACTIVE , // 有效 (输出)
IO_INACTIVE, // 无效 (输出)
};
struct GpioArgs{
struct _MyGpio *gpio;
int port;
};
struct _MyGpioPriv;
typedef struct _MyGpio {
struct _MyGpioPriv *priv;
int io_num; //GPIO数量
// 设置GPIO闪烁,并执行
void (*FlashStart)(struct _MyGpio *This,int port,int freq,int times);
// GPIO停止闪烁
void (*FlashStop)(struct _MyGpio *This,int port);
// GPIO口输出赋值,不立即执行
int (*SetValue)(struct _MyGpio *This,int port,int Value);
// GPIO口输出赋值,并立即执行
void (*SetValueNow)(struct _MyGpio *This,int port,int Value);
// 读取输入IO值,并判断是否IO有效
int (*IsActive)(struct _MyGpio *This,int port);
// 设置输入IO的输入有效电平时间
void (*setActiveTime)(struct _MyGpio *This,int port,int value);
// 检测输入IO电平 1为有效 0为无效
int (*inputHandle)(struct _MyGpio *This,int port);
// 创建输出线程
void (*addInputThread)(struct _MyGpio *This,
struct GpioArgs *args,
void *(* thread)(void *));
void (*Destroy)(struct _MyGpio *This);
}MyGpio;
void gpioInit(void);
extern MyGpio* gpio;
extern void gpioInit(void);
extern void gpioTalkDirOut(void);
extern void gpioTalkDirIn(void);
extern void gpioChargeState(int state);
extern void gpioLowPowerState(int state);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/ucpaas/ucpaas.h
/*
* =============================================================================
*
* Filename: ucpaas.h
*
* Description: 云之讯对讲接口
*
* Version: 1.0
* Created: 2019-06-05 17:28:39
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _UCPAAS_SDK_H
#define _UCPAAS_SDK_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef struct _Callbacks {
void (*dialFail)(void *arg);
void (*answer)(void *arg);
void (*hangup)(void *arg);
void (*dialRet)(void *arg);
void (*incomingCall)(void *arg);
void (*sendCmd)(void *arg);
void (*receivedCmd)(const char *user_id,void *arg);
void (*initAudio)(unsigned int rate,unsigned int bytes_per_sample,unsigned int channle);
void (*startRecord)(unsigned int rate,unsigned int bytes_per_sample,unsigned int channle);
void (*recording)(char *data,unsigned int size);
void (*playAudio)(const char *data,unsigned int size);
}Callbacks;
void ucsDial(char *user_id);
void ucsAnswer(void);
void ucsHangup(void);
void ucsSendCmd(char *cmd,char *user_id);
void ucsSendVideo(const unsigned char* frameData, const unsigned int dataLen);
int ucsConnect(char *user_token);
void ucsDisconnect(void);
void registUcpaas(Callbacks *interface);
void ucsReceiveVideo(unsigned char* frameData,
unsigned int *dataLen,
long long *timeStamp,
int *frameType);
int ucsConnectState(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/drivers/json_dec.h
/*
* =============================================================================
*
* Filename: CjsonDec.h
*
* Description: json编解码封装
*
* Version: 1.0
* Created: 2016-07-06 17:23:53
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _CJSON_DEC_H
#define _CJSON_DEC_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include "cJSON.h"
typedef struct _CjsonDec {
cJSON *root;
cJSON *current;
cJSON *front;
void (*getValueChar)(struct _CjsonDec *,char *name,char **value);
int (*getValueInt)(struct _CjsonDec *,char *name);
int (*getArrayInt)(struct _CjsonDec *,int item,char *name);
void (*getArrayChar)(struct _CjsonDec *,int item,char *name,char **value);
int (*changeCurrentObj)(struct _CjsonDec *,char *name);
cJSON* (*getValueObject)(struct _CjsonDec *This,char *name);
void (*changeCurrentArrayObj)(struct _CjsonDec *,int item);
void (*changeObjFront)(struct _CjsonDec *);
int (*getArraySize)(struct _CjsonDec *);
void (*print)(struct _CjsonDec *);
void (*destroy)(struct _CjsonDec *);
}CjsonDec;
CjsonDec *cjsonDecCreate(char *data);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/wireless/tcp_client.h
/*
* =============================================================================
*
* Filename: tcp_client.h
*
* Description: TCP客户端
*
* Version: 1.0
* Created: 2019-06-18 13:40:50
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _TCP_CLIENT_H
#define _TCP_CLIENT_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef struct _TTCPClient {
int m_socket;
void (* Destroy)(struct _TTCPClient *This);
int (* Connect)(struct _TTCPClient *This,const char *IP,int port,int TimeOut);
void (*DisConnect)(struct _TTCPClient *This);
int (* RecvBuffer)(struct _TTCPClient *This,void *buf,int count,int TimeOut);
int (* SendBuffer)(struct _TTCPClient *This,const void *buf,int count);
} TTCPClient;
// 创建一个UDP客户端,Port为0则不绑定端口
TTCPClient* TTCPClient_Create(void);
extern TTCPClient* tcp_client;
void tcpClientInit(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/gui/form_setting_date.c
/*
* =============================================================================
*
* Filename: form_setting_Date.c
*
* Description: 日期设置界面
*
* Version: 1.0
* Created: 2018-03-01 23:32:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include "externfunc.h"
#include "screen.h"
#include "config.h"
#include "my_audio.h"
#include "my_button.h"
#include "my_scroll.h"
#include "my_title.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formSettingDateProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void buttonExitPress(HWND hwnd, int id, int nc, DWORD add_data);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_SET_LOCAL > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define BMP_LOCAL_PATH "setting/"
enum {
IDC_TIMER_1S = IDC_FORM_SETTING_DATE,
IDC_BUTTON_EXIT,
IDC_BUTTON_TITLE,
IDC_MYSCROLL_YEAR,
IDC_MYSCROLL_MONTH,
IDC_MYSCROLL_DATE,
IDC_TITLE,
};
struct ScrollviewItem {
char title[32]; // 左边标题
char text[32]; // 右边文字
int (*callback)(HWND,void (*callback)(void)); // 点击回调函数
int index; // 元素位置
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static int bmp_load_finished = 0;
static int flag_Date_stop = 0;
static BmpLocation bmp_load[] = {
{NULL},
};
static MY_CTRLDATA ChildCtrls [] = {
};
static MyCtrlButton ctrls_button[] = {
{0},
};
static MyCtrlScroll ctrls_scroll[] = {
{IDC_MYSCROLL_YEAR, 0,"年",2019, 2037, 153,100,180,400},
{IDC_MYSCROLL_MONTH,0,"月",1, 12, 423,100,180,400},
{IDC_MYSCROLL_DATE, 0,"日",1, 31, 692,100,180,400},
{0},
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
// WS_EX_AUTOSECONDARYDC,
WS_EX_NONE,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "FsetDate",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formSettingDateProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
.auto_close_time_set = 30,
};
static MyCtrlTitle ctrls_title[] = {
{
IDC_TITLE,
MYTITLE_LEFT_EXIT,
MYTITLE_RIGHT_NULL,
0,0,1024,40,
"日期设置",
"",
0xffffff, 0x333333FF,
buttonExitPress,
},
{0},
};
static FormBase* form_base = NULL;
static void enableAutoClose(void)
{
Screen.setCurrent(form_base_priv.name);
flag_Date_stop = 0;
}
static void reloadDate(void)
{
struct tm *tm = getTime();
SendMessage(GetDlgItem(form_base->hDlg,IDC_MYSCROLL_YEAR),MSG_SET_NUM,tm->tm_year+1900,0);
SendMessage(GetDlgItem(form_base->hDlg,IDC_MYSCROLL_MONTH),MSG_SET_NUM,tm->tm_mon+1,0);
SendMessage(GetDlgItem(form_base->hDlg,IDC_MYSCROLL_DATE),MSG_SET_NUM,tm->tm_mday,0);
}
/* ----------------------------------------------------------------*/
/**
* @brief buttonExitPress 退出按钮
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ----------------------------------------------------------------*/
static void buttonExitPress(HWND hwnd, int id, int nc, DWORD add_data)
{
struct tm *tm = getTime();
int year = SendMessage(GetDlgItem(form_base->hDlg,IDC_MYSCROLL_YEAR),MSG_GET_NUM,0,0);
int mon = SendMessage(GetDlgItem(form_base->hDlg,IDC_MYSCROLL_MONTH),MSG_GET_NUM,0,0);
int day = SendMessage(GetDlgItem(form_base->hDlg,IDC_MYSCROLL_DATE),MSG_GET_NUM,0,0);
adjustdate(year,mon,day,tm->tm_hour,tm->tm_min,tm->tm_sec);
ShowWindow(GetParent(hwnd),SW_HIDE);
}
void formSettingDateLoadBmp(void)
{
if (bmp_load_finished == 1)
return;
printf("[%s]\n", __FUNCTION__);
bmpsLoad(bmp_load);
my_scroll->bmpsLoad(ctrls_scroll,BMP_LOCAL_PATH);
bmp_load_finished = 1;
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_title[i].idc != 0; i++) {
ctrls_title[i].font = font20;
createMyTitle(hDlg,&ctrls_title[i]);
}
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
createMyButton(hDlg,&ctrls_button[i]);
}
for (i=0; ctrls_scroll[i].idc != 0; i++) {
ctrls_scroll[i].font = font22;
createMyScroll(hDlg,&ctrls_scroll[i]);
}
reloadDate();
}
/* ----------------------------------------------------------------*/
/**
* @brief formSettingDateProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ----------------------------------------------------------------*/
static int formSettingDateProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
switch(message) // 自定义消息
{
case MSG_TIMER:
{
if (flag_Date_stop)
return 0;
} break;
case MSG_ENABLE_WINDOW:
enableAutoClose();
break;
case MSG_DISABLE_WINDOW:
flag_Date_stop = 1;
break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormSettingDate(HWND hMainWnd,void (*callback)(void))
{
HWND Form = Screen.Find(form_base_priv.name);
if(Form) {
Screen.setCurrent(form_base_priv.name);
reloadDate();
ShowWindow(Form,SW_SHOWNORMAL);
} else {
if (bmp_load_finished == 0) {
return 0;
}
form_base_priv.callBack = callback;
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
<file_sep>/module/updater/partition/partition.h
#ifndef _PARTTITION_H_
#define _PARTTITION_H_
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdarg.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mount.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <pwd.h>
#include <errno.h>
#include <signal.h>
#include <linux/watchdog.h>
#include <linux/reboot.h>
#include <time.h>
#include "httpd.h"
#include "display.h"
typedef unsigned int uint32;
typedef unsigned short uint16;
typedef unsigned char uint8;
#define RK_PARTITION_TAG (0x50464B52)
typedef enum {
PART_VENDOR = 1 << 0,
PART_IDBLOCK = 1 << 1,
PART_KERNEL = 1 << 2,
PART_BOOT = 1 << 3,
PART_RECOVERY = 1 << 4,
PART_DTB = 1 << 5,
PART_UBOOT = 1 << 6,
PART_USER = 1 << 31
} enum_parttion_type;
typedef struct {
uint16 year;
uint8 month;
uint8 day;
uint8 hour;
uint8 min;
uint8 sec;
uint8 reserve;
} struct_datetime, *pstruct_datetime;
typedef struct {
uint32 uiFwTag; //"RKFP"
struct_datetime dtReleaseDataTime;
uint32 uiFwVer;
uint32 uiSize;//size of sturct,unit of uint8
uint32 uiPartEntryOffset;//unit of sector
uint32 uiBackupPartEntryOffset;
uint32 uiPartEntrySize;//unit of uint8
uint32 uiPartEntryCount;
uint32 uiFwSize;//unit of uint8
uint8 reserved[464];
uint32 uiPartEntryCrc;
uint32 uiHeaderCrc;
} struct_fw_header, *pstruct_fw_header;
typedef struct {
uint8 szName[32];
enum_parttion_type emPartType;
uint32 uiPartOffset;//unit of sector
uint32 uiPartSize;//unit of sector
uint32 uiDataLength;//unit of uint8
uint32 uiPartProperty;
uint8 reserved[76];
} struct_part_entry, *pstruct_part_entry;
typedef struct {
struct_fw_header hdr; //0.5KB
struct_part_entry part[12]; //1.5KB
} struct_part_info, *pstruct_part_info;
typedef struct tag_kernel_hdr {
unsigned char magic[16]; // "KERNEL"
unsigned int loader_load_addr; /* physical load addr ,default is 0x60000000*/
unsigned int loader_load_size; /* size in bytes */
unsigned int crc32; /* crc32 */
unsigned int hash_len; /* 20 or 32 , 0 is no hash*/
unsigned char hash[32]; /* sha */
unsigned int js_hash;
unsigned char reserved[1024 - 32 - 32 - 4];
uint32 signTag; //0x4E474953, 'N' 'G' 'I' 'S'
uint32 signlen; //256
unsigned char rsaHash[256];
unsigned char reserved2[2048 - 1024 - 256 - 8];
} kernel_hdr; //Size:2K
typedef struct Setting_ini_info {
char UserPart[40];
char szname[40];
char storge_path[40];
char mount_path[40];
int type;
} struct_setting_ini;
class RKPartition
{
private:
unsigned int getFileSize(char* filename);
int readFile(int fd, void *buffer, int size);
int writeFile(int fd, void *buffer, int size);
int getFwPartInfo(struct_part_info *Info);
int getStoragePartInfo(struct_part_info *Info);
int setStoragePartInfo(struct_part_info *Info);
int setPartBootPriority(struct_part_info *Info, int parttype);
void debugPartsInfos(struct_part_info *info);
int checkPartsInfos();
int checkKernelCRC(char *path, kernel_hdr *hdr);
int checkImage(char *partname);
int checkImage(int parttype);
unsigned int getPartOffset_bytype(struct_part_info info, uint32 type);
int getPartIndex_bytype(struct_part_info info, uint32 type);
int getAPartIndex_bytype(struct_part_info info, uint32 type);
int getBPartIndex_bytype(struct_part_info info, uint32 type);
unsigned int getPartOffset_byname(struct_part_info info, char *name);
int getPartIndex_byname(struct_part_info info, char *name);
int updatePart(struct_setting_ini info);
int fwPartitionInit();
int partitionInit(char *partname);
int partitionInit(int parttype);
public:
int setImagePath(char *name);
int setImageType(int type);
int checkPartitions(int parttype);
int RKPartition_init();
int update(int parttype);
RKPartition(RKDisplay *disp = NULL);
~RKPartition();
struct_part_info mPartInfo;
struct_part_info mFWPartInfo;
kernel_hdr mKernelHdr;
kernel_hdr mFWKernelHdr;
char imagepath[40];
int imagetype;
RKDisplay* RKdisp;
struct disp_rect box_rect;
struct disp_rect fill_rect;
struct disp_cap cap;
};
#endif
<file_sep>/src/app/externfunc.c
/*
* =====================================================================================
*
* Filename: externfunc.c
*
* Description: 外部函数
*
* Version: 1.0
* Created: 2015-12-11 11:56:30
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
/* ----------------------------------------------------------------*
* include head files
*-----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <strings.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <netinet/ip.h>
#include <net/if.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <signal.h>
#include <linux/rtc.h>
#include <linux/fb.h>
#include <linux/types.h>
#include <linux/watchdog.h>
#include <sys/statfs.h>
#include <sys/mman.h>
#include "debug.h"
#include "thread_helper.h"
#include "externfunc.h"
#include "config.h"
/* ----------------------------------------------------------------*
* extern variables declare
*-----------------------------------------------------------------*/
extern int iwlist(int argc,
char ** argv,void *ap_info,int *ap_cnt);
extern int
iwconfig(int argc,
char ** argv,int *qual);
/* ----------------------------------------------------------------*
* internal functions declare
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*
* macro define
*-----------------------------------------------------------------*/
#define IOCTL_PD 0x1001
#define IOCTL_PU 0x1002
#define IOCTL_NM 0x1003
/* ----------------------------------------------------------------*
* variables define
*-----------------------------------------------------------------*/
static void (*wifiloadCallback)(void *ap_info,int ap_cnt);
static int wifi_scan_end = 1;
/* ---------------------------------------------------------------------------*/
/**
* @brief GetDate 取当前日期时间格式
*
* @param cBuf
* @param Size
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
char * getDate(char *cBuf,int Size)
{
time_t timer;
struct tm *tm1;
if(Size<20) {
if(cBuf) cBuf[0]=0;
return cBuf;
}
timer = time(&timer);
tm1 = localtime(&timer);
sprintf(cBuf,
"%04d-%02d-%02d %02d:%02d:%02d",
tm1->tm_year+1900,
tm1->tm_mon+1,
tm1->tm_mday,
tm1->tm_hour,
tm1->tm_min,
tm1->tm_sec);
return cBuf;
}
void getFileName(char *file_name,char *date)
{
if (!file_name || !date)
return;
time_t timer;
struct tm *tm1;
timer = time(&timer);
tm1 = localtime(&timer);
sprintf(file_name,
"%02d%02d%02d%02d%02d%02d",
(tm1->tm_year+1900) % 100,
tm1->tm_mon+1,
tm1->tm_mday,
tm1->tm_hour,
tm1->tm_min,
tm1->tm_sec);
sprintf(date,
"%04d-%02d-%02d %02d:%02d:%02d",
tm1->tm_year+1900,
tm1->tm_mon+1,
tm1->tm_mday,
tm1->tm_hour,
tm1->tm_min,
tm1->tm_sec);
}
struct tm * getTime(void)
{
time_t timer;
timer = time(&timer);
return localtime(&timer);
}
int adjustdate(int year,int mon,int mday,int hour,int min,int sec)
{
//设备系统时间
int rtc;
time_t t;
struct tm nowtime;
nowtime.tm_sec=sec; /* Seconds.[0-60] (1 leap second)*/
nowtime.tm_min=min; /* Minutes.[0-59] */
nowtime.tm_hour=hour; /* Hours. [0-23] */
nowtime.tm_mday=mday; /* Day.[1-31] */
nowtime.tm_mon=mon-1; /* Month. [0-11] */
nowtime.tm_year=year-1900; /* Year- 1900. */
nowtime.tm_isdst=-1; /* DST.[-1/0/1] */
t=mktime(&nowtime);
stime(&t);
//设置实时时钟
rtc = open("/dev/rtc0",O_WRONLY);
if(rtc<0) {
rtc = open("/dev/misc/rtc",O_WRONLY);
if(rtc<0) {
printf("can't open /dev/misc/rtc\n");
return -1;
}
}
if (ioctl(rtc, RTC_SET_TIME, &nowtime ) < 0 ) {
printf("Could not set the RTC time\n");
close(rtc);
return -1;
}
close(rtc);
return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief getMs 获得当前系统毫秒数
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
uint64_t getMs(void)
{
struct timeval tv;
gettimeofday(&tv,NULL);
return ((tv.tv_usec / 1000) + tv.tv_sec * 1000 );
}
/* ---------------------------------------------------------------------------*/
/**
* @brief fileexists 判断文件是否存在
*
* @param FileName 文件名
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
int fileexists(const char *FileName)
{
int ret = access(FileName,0);
return ret == 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief strupper 小写转大写
*
* @param pdst
* @param pstr
* @param Size
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
char *strupper(char *pdst,const char *pstr,int Size)
{
char *pchar = pdst;
if(pstr==NULL)
return NULL;
strncpy(pdst,pstr,Size);
while(*pchar) {
if(*pchar>='a' && *pchar<='z')
*pchar = *pchar - 'a' + 'A';
pchar++;
}
return pdst;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief DelayMs 线程使用 延时毫秒
*
* @param ms
*/
/* ---------------------------------------------------------------------------*/
void DelayMs(int ms)
{
#if 0
unsigned long long start_time;
start_time = getMs();
while (!(getMs() - start_time >= ms)) ;
#else
usleep(ms*1000);
#endif
}
/* ---------------------------------------------------------------------------*/
/**
* @brief excuteCmd 执行shell命令,以NULL结尾
*
* @param Cmd
* @param ...
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static char cmd_buf[1024] = {0};
char * excuteCmd(char *Cmd,...)
{
int i;
FILE *fp;
int ret;
va_list argp;
char *argv;
char commond[512] = {0};
strcat(commond,Cmd);
va_start( argp, Cmd);
for(i=1;i<20;i++) {
argv = va_arg(argp,char *);
if(argv == NULL)
break;
strcat(commond," ");
strcat(commond,argv);
}
va_end(argp);
// DPRINT("cmd :%s\n",commond);
if ((fp = popen(commond, "r") ) == 0) {
perror("popen");
return NULL;
}
memset(cmd_buf,0,sizeof(cmd_buf));
ret = fread( cmd_buf, sizeof(cmd_buf), sizeof(char), fp ); //将刚刚FILE* stream的数据流读取到cmd_buf
// DPRINT("r:%d\n",ret );
if ( (ret = pclose(fp)) == -1 ) {
DPRINT("close popen file pointer fp error!\n");
}
return cmd_buf;
// 用此函数导致产生僵尸进程
// system(commond);
// return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief recoverData 恢复数据
*
* @param file 文件名称
* @param reboot 1需要重启 0不需要重启
*/
/* ---------------------------------------------------------------------------*/
int recoverData(const char *file)
{
int size = strlen(file);
char *backfile = (char *) malloc (sizeof(char) * size + 5);
sprintf(backfile,"%s_bak",file);
if (fileexists(backfile)) {
excuteCmd("cp",backfile,file,NULL);
sync();
free(backfile);
return 1;
}
free(backfile);
return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief backData 备份数据
*
* @param file
*/
/* ---------------------------------------------------------------------------*/
void backData(char *file)
{
int size = strlen(file);
char *backfile = (char *) malloc (sizeof(char) * size + 5);
sprintf(backfile,"%s_bak",file);
excuteCmd("cp",file,backfile,NULL);
sync();
free(backfile);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief GetSendIP 判断本地IP与目标IP是否同一个网段,
* 如果不在同一个网段将返回最小的广播域
*
* @param pSrcIP 本地IP地址
* @param pDestIP 目标IP地址
* @param pMask 本机子网掩码
*
* @returns 最小的广播域IP地址
*/
/* ---------------------------------------------------------------------------*/
const char * GetSendIP(const char *pSrcIP,const char *pDestIP,const char *pMask)
{
//取广播域
static char cIP[16];
unsigned int SrcIP,DestIP,Mask;
unsigned char *pIP = (unsigned char *)&DestIP;
//转换字符形IP到整形IP地址
SrcIP = inet_addr(pSrcIP);
DestIP = inet_addr(pDestIP);
Mask = inet_addr(pMask);
if((SrcIP & Mask)!=(DestIP & Mask)) {
DestIP = (SrcIP & Mask) | (~Mask & 0xFFFFFFFF);//DestIP = 0xFFFFFFFF;
}
//转换成字符形IP地址
sprintf(cIP,"%d.%d.%d.%d",pIP[0],pIP[1],pIP[2],pIP[3]);
return cIP;
}
int getLocalIP(char *ip,char *gateway)
{
struct ifreq ifr;
int sock;
if((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
return 0;
}
strcpy(ifr.ifr_name, "wlan0");
if(ioctl(sock, SIOCGIFADDR, &ifr) < 0)
goto error;
strcpy(ip,(char*)inet_ntoa(((struct sockaddr_in *)(&ifr.ifr_addr))->sin_addr));
char *ret = excuteCmd("route","|","grep","default",NULL);
sscanf(ret, "%*s %s",gateway);
close(sock);
return 1;
error:
close(sock);
return 0;
}
int getGateWayMac(char *gateway,char *mac)
{
char *ret = excuteCmd("arp","-a",gateway,NULL);
sscanf(ret, "%*s %*s %*s %s",mac);
return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief jugdeRecIP 判断目标IP和本机IP是否在同一网段
*
* @param pSrcIP 本机IP
* @param pDestIP 目标IP
* @param pMask 本机掩码
*
* @returns 0不在同一网段 1在同一网段
*/
/* ---------------------------------------------------------------------------*/
int jugdeRecIP(const char *pSrcIP,const char *pDestIP,const char *pMask)
{
unsigned int SrcIP,DestIP,Mask;
//转换字符形IP到整形IP地址
SrcIP = inet_addr(pSrcIP);
DestIP = inet_addr(pDestIP);
Mask = inet_addr(pMask);
if((SrcIP & Mask)!=(DestIP & Mask))
return 0;
return 1;
}
/* ----------------------------------------------------------------*/
/**
* @brief GetFileSize 获得文件大小
*
* @param file 文件名
*
* @returns
*/
/* ----------------------------------------------------------------*/
int GetFileSize(char *file)
{
struct stat stat_buf;
stat(file, &stat_buf) ;
return stat_buf.st_size;
}
uint64_t MyGetTickCount(void)
{
return time(NULL)*1000;
}
/* ----------------------------------------------------------------*/
/**
* @brief print_data 格式化打印数据
*
* @param data 数据内容
* @param len 长度
*/
/* ----------------------------------------------------------------*/
void print_data(char *data,int len)
{
int i;
for (i = 0; i < len; ++i) {
if (i) {
DPRINT("[%02d]0x%02x ",i,data[i] );
if ((i%5) == 0)
DPRINT("\n");
} else {
DPRINT("\n");
}
}
DPRINT("\n");
}
/* ----------------------------------------------------------------*/
/**
* @brief GetFilesNum 获取文件夹目录文件名及返回文件数目
*
* @param pPathDir 文件夹目录
* @param func 每获得一个文件处理函数
*
* @returns 文件夹目录下的文件数目
*/
/* ----------------------------------------------------------------*/
int GetFilesNum(char *pPathDir,void (*func)(void *))
{
// int i=0 ;
// DIR *dir = NULL;
// struct dirent *dirp = NULL;
// struct _st_dir temp_file; // 保存文件名结构体
// if((dir=opendir(pPathDir)) == NULL) {
// DPRINT("Open File %s Error %s\n",pPathDir,strerror(errno));
// return 0;
// }
// while((dirp=readdir(dir)) != NULL) {
// if ((strcmp(".",dirp->d_name) == 0) || (strcmp("..",dirp->d_name) == 0)) {
// continue;
// }
// i++;
// sprintf(temp_file.path,"%s/%s",pPathDir,dirp->d_name);
// if (func) {
// func(&temp_file);
// }
// // DPRINT("i:%d,name:%s\n",i,dirp->d_name);
// }
// closedir(dir);
// return i;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief getDiffSysTick 计算32位差值
*
* @param new
* @param old
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
uint32_t getDiffSysTick(uint64_t new,uint64_t old)
{
uint32_t diff;
if (new >= old)
diff = new - old;
else
diff = 0XFFFFFFFF - old + new;
return diff;
}
static void* getWifiListThread(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
TcWifiScan *plist = (TcWifiScan *)arg;
char *cmd[] = { "cat_eye", "wlan0", "scan" };
int cnt = 0;
// 移植iwlist,传入需要的值
iwlist(3,cmd,plist,&cnt);
if (wifiloadCallback)
wifiloadCallback(plist,cnt);
wifi_scan_end = 1;
return NULL;
}
int getWifiList(void *ap_info,void (*callback)(void *ap_info,int ap_cnt))
{
if (wifi_scan_end == 0)
return 0;
wifi_scan_end = 0;
wifiloadCallback = callback;
return createThread(getWifiListThread,ap_info);
}
int getWifiConfig(int *qual)
{
#ifdef X86
*qual = 2;
return 0;
#else
char *cmd[] = { "cat_eye", "wlan0" };
iwconfig(2,cmd,qual);
char *state = excuteCmd("wpa_cli","-iwlan0","status","|","grep","wpa_state",NULL);
if (strncmp(state,"wpa_state=COMPLETED",strlen("wpa_state=COMPLETED")))
return 1;
else
return 0;
#endif
}
void wifiConnectStart(void)
{
#ifndef X86
excuteCmd("ifconfig","wlan0","up",NULL);
#endif
}
void wifiConnect(void)
{
#ifndef X86
// 用 excuteCmd 会阻塞
system("./wifi/wifi_start.sh &");
#endif
}
void wifiDisConnect(void)
{
#ifndef X86
excuteCmd("wifi/wifi_station.sh","stop",NULL);
#endif
}
int screenSetBrightness(int brightness)
{
#define MIN_BRIGHTNESS 244
#define MAX_BRIGHTNESS 0
#ifndef X86
char buf[4] = {0};
// 当设置为100时,亮度设置为0,此时灭屏,最大设置99
if (brightness == 100)
brightness--;
int real_brightness = (100 - brightness)*(MIN_BRIGHTNESS - MAX_BRIGHTNESS) / 100;
sprintf(buf,"%d",real_brightness);
excuteCmd("echo",buf,">","/sys/class/backlight/rk28_bl/brightness ",NULL);
#endif
}
int screensaverSet(int state)
{
#ifndef X86
static int state_old = 0;
if (state == state_old)
return 0;
state_old = state;
if (state)
screenSetBrightness(g_config.brightness);
else
screenSetBrightness(0);
#endif
return 1;
}
void getCpuId(char *hardcode)
{
#ifndef X86
FILE *fp = fopen("/proc/cpuinfo","rb");
if (fp == NULL)
return;
char data[64] = {0};
while(fgets(data,sizeof(data),fp) != NULL) {
if (strncmp(data,"Serial",strlen("Serial")) == 0) {
sscanf( data, "%*s %*s %s",hardcode);
}
}
fclose(fp);
#else
strcpy(hardcode,"217aa023d24d2833");
#endif
}
void powerOff(void)
{
excuteCmd("poweroff",NULL);
}
void reboot(void)
{
excuteCmd("reboot",NULL);
}
int checkSD(void)
{
int file = -1;
#ifndef X86
file = open( "/dev/mmcblk0", O_RDONLY );
close(file);
#else
return 0;
#endif
return file;
}
int getSdMem(char *total,char *residue,char *used)
{
#ifndef X86
char *ret = excuteCmd("df","-h","|","grep","mmcblk0",NULL);
#else
char *ret = excuteCmd("df","-h","|","grep","sda1",NULL);
#endif
sscanf(ret, "%*s %s %*s %s %s",total,residue,used);
}
void getVersionInfo(char *ver,int *major,int *minor,int *release)
{
char buf[16] = {0};
char* save_ptr;
if (ver[0] == 0)
return;
strcpy(buf,ver);
*major = atoi(strtok_r(buf, ".", &save_ptr));
*minor = atoi(strtok_r(NULL, ".", &save_ptr));
*release = atoi(strtok_r(NULL, ".", &save_ptr));
}
void setSysVolume(int volume)
{
#ifndef X86
char buf[64] = {0};
sprintf(buf, "amixer cset numid=4 %d",volume);
system(buf);
#endif
}
/* ---------------------------------------------------------------------------*/
/**
* @brief getKernelVersion 读取内核版本
*
* @param version
* @param leng
*/
/* ---------------------------------------------------------------------------*/
void getKernelVersion(char *version,int leng)
{
int fd = open("/sys/devices/platform/taichuan/taichuanDev", O_RDONLY);
if (fd < 0) {
printf("get kernel version fail\n");
return;
}
if (read(fd,version,leng) <= 0)
printf("read kernel version fail\n");
close(fd);
}
<file_sep>/src/app/ucpaas/CMakeLists.txt
# 查找当前目录下的所有源文件 并将名称保存到 SRCS_UCPAAS 变量
aux_source_directory(. SRCS_UCPAAS)
STRING( REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER_UCPAAS ${CMAKE_CURRENT_SOURCE_DIR})
# 生成链接库
add_library (${CURRENT_FOLDER_UCPAAS} ${SRCS_UCPAAS})
target_link_libraries(${CURRENT_FOLDER_UCPAAS}
UCSService UcsEngine c
)
<file_sep>/src/gui/CMakeLists.txt
# 查找当前目录下的所有源文件 并将名称保存到 SRCS_GUI 变量
aux_source_directory(. SRCS_GUI)
STRING( REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER_GUI ${CMAKE_CURRENT_SOURCE_DIR})
set(SUB_DIRS_GUI
my_controls
)
foreach(sub ${SUB_DIRS_GUI})
add_subdirectory(${sub})
endforeach()
# 生成链接库
add_library (${CURRENT_FOLDER_GUI} ${SRCS_GUI})
target_link_libraries (${CURRENT_FOLDER_GUI} ${SUB_DIRS_GUI})
<file_sep>/src/drivers/linklist.h
/*
* =====================================================================================
*
* Filename: LinkList.h
*
* Description: 通用链表函数
*
* Version: 1.0
* Created: 2015-11-04 16:11:54
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
#ifndef _LINK_LIST_H
#define _LINK_LIST_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
// #define TEST
#define LISTLINK_OK 1
#define LISTLINK_FAIL 0
struct _ListPriv;
typedef struct _List{
struct _ListPriv *priv;
void (*clear)(struct _List*); /* 清空链表 */
int (*append)(struct _List*,void *); /* 追加元素 */
int (*insert)(struct _List*,int,void *); /* 加入元素 */
int (*delete)(struct _List *,int); /* 删除第几个元素 */
int (*foreachStart)(struct _List*,int ); /* 开始遍历 */
int (*foreachNext)(struct _List*); /* 遍历下一个 */
int (*foreachGetElem)(struct _List*,void *); /* 获取遍历元素 */
int (*foreachEnd)(struct _List*); /* 判断是否遍历结束 */
int (*getElem)(struct _List*,int,void * ); /* 取得第几个元素的值用第三个参数返回 */
int (*getElemTail)(struct _List*,void *); /* 取得最后一个元素的内容 */
int (*traverse)(struct _List*,int (*)(void * )); /* 遍历访问,访问某个节点元素用函数处理 */
void (*destory)(struct _List*); /* 销毁链表 */
}List;
List * listCreate(unsigned int size); /* 创建链表 */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/wireless/my_http.c
/*
* =============================================================================
*
* Filename: my_http.c
*
* Description: 封装tcp/ip接口
*
* Version: 1.0
* Created: 2019-05-21 11:32:29
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "my_http.h"
#include "curl/curl.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
struct MemoryStruct {
char *memory;
size_t size;
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
MyHttp *my_http = NULL;
static long download_size = 0; // 当前下载文件大小
static long download_total_size = 0; // 下载文件总大小
static UpdateFunc downloadCallback = NULL; // 下载文件回调函数,用于UI显示
static long getDownloadFileLenth(CURL *handle,const char *url)
{
double downloadFileLenth = 0;
curl_easy_setopt(handle, CURLOPT_URL, url);
curl_easy_setopt(handle, CURLOPT_HEADER, 1); //只需要header头
curl_easy_setopt(handle, CURLOPT_NOBODY, 1); //不需要body
if (curl_easy_perform(handle) == CURLE_OK) {
curl_easy_getinfo(handle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &downloadFileLenth);
}
curl_easy_reset(handle);
return downloadFileLenth;
}
static size_t downloadCallBackData(void *buffer, size_t size, size_t nmemb, void *user_p)
{
int pos = 0;
download_size += nmemb;
if (download_total_size)
pos = download_size * 100 / download_total_size;
if (downloadCallback)
downloadCallback(UPDATE_POSITION,pos);
return fwrite(buffer, size, nmemb, user_p);
}
static size_t postCallBackData(void *buffer, size_t size, size_t nmemb, void *user_p)
{
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)user_p;
mem->memory = (char *)realloc(mem->memory, mem->size + realsize + 1);
if(mem->memory == NULL) {
/* out of memory! */
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), buffer, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
static size_t qiniuPostCallBackData(void *buffer, size_t size, size_t nmemb, void *user_p)
{
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)user_p;
mem->memory = (char *)realloc(mem->memory, mem->size + realsize + 1);
if(mem->memory == NULL) {
/* out of memory! */
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), buffer, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
static int download(char *url, char *para, char *file_path,UpdateFunc callback)
{
if (!url) {
printf("NULL url!!\n");
return -1;
}
CURLcode r = CURLE_GOT_NOTHING;
CURL *easy_handle = curl_easy_init();
if (!easy_handle) {
printf("NULL easy_handle!!\n");
return -1;
}
downloadCallback = callback;
download_total_size = getDownloadFileLenth(easy_handle,url);
curl_easy_setopt(easy_handle,CURLOPT_URL,url);
// curl_easy_setopt(easy_handle, CURLOPT_POST, 1);
if (para)
curl_easy_setopt(easy_handle, CURLOPT_POSTFIELDS, para);
download_size = 0;
FILE *fd = NULL;
fd = fopen(file_path, "wb");
if (fd == NULL)
goto EXIT;
curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, fd);
curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, &downloadCallBackData);
curl_easy_setopt(easy_handle, CURLOPT_SSL_VERIFYHOST, 0L);
r = curl_easy_setopt(easy_handle, CURLOPT_SSL_VERIFYPEER, 0L);
if (r != CURLE_OK) {
printf("curl download CURLOPT_SSL_VERIFYPEER failed :%s\n",curl_easy_strerror(r));
goto CLOSE_FD_EXIT;
}
r = curl_easy_perform(easy_handle);
if (r != CURLE_OK) {
printf("curl download failed :%s\n",curl_easy_strerror(r));
}
CLOSE_FD_EXIT:
fflush(fd);
fclose(fd);
sync();
EXIT:
curl_easy_cleanup(easy_handle);
downloadCallback = NULL;
return download_size;
}
static int post(char *url, char *para, char **out_data)
{
if (!url) {
printf("NULL url!!\n");
return 0;
}
CURLcode r = CURLE_GOT_NOTHING;
CURL *easy_handle = curl_easy_init();
if (!easy_handle) {
printf("NULL easy_handle!!\n");
return 0;
}
curl_easy_setopt(easy_handle,CURLOPT_URL,url);
// curl_easy_setopt(easy_handle, CURLOPT_POST, 1);
if (para)
curl_easy_setopt(easy_handle, CURLOPT_POSTFIELDS, para);
struct MemoryStruct chunk;
chunk.memory = (char *)malloc(sizeof(char)); /* will be grown as needed by the realloc above */
chunk.size = 0; /* no data at this point */
curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, &postCallBackData);
curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, (void *)&chunk);
curl_easy_setopt(easy_handle, CURLOPT_SSL_VERIFYHOST, 0L);
r = curl_easy_setopt(easy_handle, CURLOPT_SSL_VERIFYPEER, 0L);
if (r != CURLE_OK) {
if (chunk.memory)
free(chunk.memory);
printf("curl post CURLOPT_SSL_VERIFYPEER failed :%s\n",curl_easy_strerror(r));
goto EXIT;
}
r = curl_easy_perform(easy_handle);
if (r != CURLE_OK) {
if (chunk.memory)
free(chunk.memory);
printf("curl post failed :%s\n",curl_easy_strerror(r));
goto EXIT;
}
*out_data = chunk.memory;
EXIT:
curl_easy_cleanup(easy_handle);
return chunk.size;
}
static int qiniuUpload(char *url,
char *para,
char *token,
char *file_path,
char *file_name,
char **out_data)
{
if (!url) {
printf("NULL url!!\n");
return 0;
}
struct curl_httppost* formpost = NULL;
struct curl_httppost* lastptr = NULL;
CURLcode r = CURLE_GOT_NOTHING;
CURL *easy_handle = curl_easy_init();
if (!easy_handle) {
printf("NULL easy_handle!!\n");
return 0;
}
curl_formadd(&formpost, &lastptr,
CURLFORM_COPYNAME, "key",
CURLFORM_COPYCONTENTS, file_name, CURLFORM_END);
curl_formadd(&formpost, &lastptr,
CURLFORM_COPYNAME, "token",
CURLFORM_COPYCONTENTS, token, CURLFORM_END);
curl_formadd(&formpost, &lastptr,
CURLFORM_COPYNAME, "file",
CURLFORM_FILE, file_path, CURLFORM_END);
// 设置表单参数
curl_easy_setopt(easy_handle, CURLOPT_HTTPPOST, formpost);
curl_easy_setopt(easy_handle,CURLOPT_URL,url);
// curl_easy_setopt(easy_handle, CURLOPT_POST, 1);
if (para)
curl_easy_setopt(easy_handle, CURLOPT_POSTFIELDS, para);
struct MemoryStruct chunk;
chunk.memory = (char *)malloc(sizeof(char)); /* will be grown as needed by the realloc above */
chunk.size = 0; /* no data at this point */
curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, &qiniuPostCallBackData);
curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, (void *)&chunk);
curl_easy_setopt(easy_handle, CURLOPT_SSL_VERIFYHOST, 0L);
r = curl_easy_setopt(easy_handle, CURLOPT_SSL_VERIFYPEER, 0L);
if (r != CURLE_OK) {
if (chunk.memory)
free(chunk.memory);
printf("curl post CURLOPT_SSL_VERIFYPEER failed :%s\n",curl_easy_strerror(r));
goto EXIT;
}
r = curl_easy_perform(easy_handle);
if (r != CURLE_OK) {
if (chunk.memory)
free(chunk.memory);
printf("curl post failed :%s\n",curl_easy_strerror(r));
goto EXIT;
}
*out_data = chunk.memory;
EXIT:
curl_easy_cleanup(easy_handle);
return chunk.size;
}
MyHttp * myHttpCreate(void)
{
// 只创建一次接口
if (my_http)
return my_http;
my_http = (MyHttp *) calloc(1,sizeof(MyHttp));
my_http->post = post;
my_http->download = download;
my_http->qiniuUpload = qiniuUpload;
curl_global_init(CURL_GLOBAL_ALL);
return my_http;
}
<file_sep>/module/video/process/md_display_process.cpp
#include "md_display_process.h"
#include "thread_helper.h"
#include "h264_enc_dec/mpi_dec_api.h"
#include "jpeg_enc_dec.h"
#include "libyuv.h"
static FILE *fp = NULL;
int NV12Scale(unsigned char *psrc_buf, int psrc_w, int psrc_h, unsigned char **pdst_buf, int pdst_w, int pdst_h);
static void writePicture(DisplayProcess *This,unsigned char *data)
{
if (fp == NULL)
return;
unsigned char *jpeg_buf = NULL;
int size = 0;
yuv420spToJpeg(data,1280,720,&jpeg_buf,&size);
if (jpeg_buf) {
fwrite(jpeg_buf,1,size,fp);
fflush(fp);
fclose(fp);
free(jpeg_buf);
}
fp = NULL;
}
DisplayProcess::DisplayProcess()
: StreamPUBase("DisplayProcess", true, true)
{
rga_fd = rk_rga_open();
if (rga_fd < 0)
printf("rk_rga_open failed\n");
}
DisplayProcess::~DisplayProcess()
{
rk_rga_close(rga_fd);
}
bool DisplayProcess::processFrame(std::shared_ptr<BufferBase> inBuf,
std::shared_ptr<BufferBase> outBuf)
{
int src_w = inBuf->getWidth();
int src_h = inBuf->getHeight();
int src_fd = (int)(inBuf->getFd());
int vir_w = src_w;
int vir_h = src_h;
int src_fmt = RGA_FORMAT_YCBCR_420_SP;
int disp_width = 0, disp_height = 0;
struct win* video_win = rk_fb_getvideowin();
int out_device = rk_fb_get_out_device(&disp_width, &disp_height);
int dst_fd = video_win->video_ion.fd;
int dst_fmt = RGA_FORMAT_YCBCR_420_SP;
int dst_w = disp_width;
int dst_h = disp_height;
int rotate_angle = (out_device == OUT_DEVICE_HDMI ? 0 : 0);
int ret = rk_rga_ionfd_to_ionfd_rotate(rga_fd,
src_fd, src_w, src_h, src_fmt, vir_w, vir_h,
dst_fd, dst_w, dst_h, dst_fmt,
rotate_angle);
if (ret) {
printf("rk_rga_ionfd_to_ionfd_rotate failed\n");
return false;
}
writePicture(this,(unsigned char *)inBuf->getVirtAddr());
if (rk_fb_video_disp(video_win) < -1){
printf("rk_fb_video_disp failed\n");
}
return true;
}
void DisplayProcess::showLocalVideo(void)
{
}
void DisplayProcess::capture(char *file_name)
{
fp = fopen(file_name,"wb");
}
<file_sep>/src/wireless/CMakeLists.txt
# 查找当前目录下的所有源文件 并将名称保存到 SRCS_WIRELESS 变量
aux_source_directory(. SRCS_WIRELESS)
STRING( REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER_WIRELESS ${CMAKE_CURRENT_SOURCE_DIR})
# 生成链接库
add_library (${CURRENT_FOLDER_WIRELESS} ${SRCS_WIRELESS})
<file_sep>/src/hal/hal_watchdog.h
/*
* =============================================================================
*
* Filename: hal_watchdog.h
*
* Description: 硬件层 看门狗接口
*
* Version: virsion
* Created: 2018-12-12 15:52:30
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _HAL_WATCHDOG_H
#define _HAL_WATCHDOG_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* ---------------------------------------------------------------------------*/
/**
* @brief halWatchDogOpen 打开看门狗
*/
/* ---------------------------------------------------------------------------*/
void halWatchDogOpen(void);
/* ---------------------------------------------------------------------------*/
/**
* @brief halWatchDogFeed 喂狗,需要时添加
*/
/* ---------------------------------------------------------------------------*/
void halWatchDogFeed(void);
/* ---------------------------------------------------------------------------*/
/**
* @brief halWatchDogClose 关闭看门狗
*/
/* ---------------------------------------------------------------------------*/
void halWatchDogClose(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/gui/my_controls/my_status.h
/*
* =============================================================================
*
* Filename: my_status.h
*
* Description: 自定义状态显示
*
* Version: 1.0
* Created: 2019-04-23 19:46:14
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_STATUS_H
#define _MY_STATUS_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include "my_controls.h"
#include "commongdi.h"
#define CTRL_MYSTATUS ("mystatus")
#define MSG_MYSTATUS_SET_LEVEL (MSG_USER + 1)
typedef struct {
BITMAP *images; // 状态图片数组
int total_level; // 总共几组状态
int level; // 当前状态
}MyStatusCtrlInfo;
typedef struct _MyCtrlStatus{
HWND idc; // 控件ID
char *img_name; // 常态图片名字,不带扩展名,完整路径由循环赋值
int16_t x,y;
int total_level; // 总共几组状态
BITMAP *images; // 状态图片数组
}MyCtrlStatus;
HWND createMyStatus(HWND hWnd,MyCtrlStatus *ctrl);
MyControls * my_status;
void initMyStatus(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/module/cap/camera/md_camerahal.cpp
#include "md_camerahal.h"
RKCameraHal::RKCameraHal(std::shared_ptr<CamHwItf> dev,
int index, int type)
:camdev(dev)
,index_(index)
,type_(type)
{
printf("[RKCameraHal:%s]\n",__func__);
if (camdev->initHw(index) == false)
printf("[RKCameraHal:%s] camdev initHw error\n",__func__);
mpath_ = camdev->getPath(CamHwItf::MP);
}
RKCameraHal::~RKCameraHal(void)
{
printf("[RKCameraHal:%s] \n",__func__);
}
void RKCameraHal::init(const uint32_t width,
const uint32_t height, const int fps)
{
printf("[RKCameraHal:%s] \n",__func__);
format_.frmSize.width = width;
format_.frmSize.height = height;
format_.frmFmt = HAL_FRMAE_FMT_NV12;
format_.colorSpace = HAL_COLORSPACE_JPEG;
format_.fps = fps;
HAL_FPS_INFO_t fps_info;
fps_info.numerator = 1;
fps_info.denominator = fps;
if (!camdev->setFps(fps_info))
printf("[RKCameraHal:%s]dev set fps is %.2f\n", __func__,
1.0 * fps_info.denominator / fps_info.numerator);
}
void RKCameraHal::start(const uint32_t num,
std::shared_ptr<RKCameraBufferAllocator> ptr_allocator)
{
printf("[RKCameraHal:%s] \n",__func__);
if (mpath()->prepare(format_, num, *ptr_allocator, false, 0) == false) {
printf("[RKCameraHal:%s] mpath prepare failed \n",__func__);
return;
}
if (!mpath()->start()) {
printf("[RKCameraHal:%s] mpath start failed \n",__func__);
return;
}
}
void RKCameraHal::stop(void)
{
printf("[RKCameraHal:%s] \n",__func__);
if (mpath().get()) {
mpath()->stop();
mpath()->releaseBuffers();
}
}
<file_sep>/src/drivers/CMakeLists.txt
# 查找当前目录下的所有源文件 并将名称保存到 SRCS_DRIVERS 变量
aux_source_directory(. SRCS_DRIVERS)
STRING( REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER_DRIVERS ${CMAKE_CURRENT_SOURCE_DIR})
set(SUB_DIRS_DRIVERS
iniparser
avilib
mp4_muxer
)
foreach(sub ${SUB_DIRS_DRIVERS})
add_subdirectory(${sub})
endforeach()
# 生成链接库
add_library (${CURRENT_FOLDER_DRIVERS} ${SRCS_DRIVERS})
target_link_libraries (${CURRENT_FOLDER_DRIVERS} ${SUB_DIRS_DRIVERS})
<file_sep>/src/gui/form_setting_qrcode.c
/*
* =============================================================================
*
* Filename: form_setting_Qrcode.c
*
* Description: Qrcode设置界面
*
* Version: 1.0
* Created: 2018-03-01 23:32:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <string.h>
#include "externfunc.h"
#include "screen.h"
#include "my_button.h"
#include "my_title.h"
#include "config.h"
#include "protocol.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static void buttonGetImei(HWND hwnd, int id, int nc, DWORD add_data);
static int formSettingQrcodeProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void buttonNotify(HWND hwnd, int id, int nc, DWORD add_data);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_SET_LOCAL > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define BMP_LOCAL_PATH "setting/"
enum {
IDC_TIMER_1S = IDC_FORM_QRCODE_STATR,
IDC_STATIC_TEXT_IMEI,
IDC_STATIC_TEXT_APP_URL,
IDC_STATIC_TEXT_HELP,
IDC_STATIC_TEXT_GETIMEI,
IDC_STATIC_IMAGE_IMEI,
IDC_STATIC_IMAGE_APP_URL,
IDC_TITLE,
IDC_BUTTON_GETIMEI,
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static int bmp_load_finished = 0;
static int flag_timer_stop = 0;
static BITMAP bmp_imei;
static BITMAP bmp_app_url;
static BITMAP bmp_null;
static BmpLocation bmp_load[] = {
{&bmp_null,BMP_LOCAL_PATH"qrcode_null.png"},
{NULL},
};
static MY_CTRLDATA ChildCtrls [] = {
STATIC_LB(170,384,220,40,IDC_STATIC_TEXT_IMEI,"设备二维码",&font22,0xffffff),
STATIC_LB(633,384,220,40,IDC_STATIC_TEXT_APP_URL,"APP下载二维码",&font22,0xffffff),
STATIC_LB(0,537,1024,40,IDC_STATIC_TEXT_HELP,"下载手机APP扫码设备二维码,添加智能猫眼设备",&font20,0xffffff),
STATIC_LB(0,497,1024,40,IDC_STATIC_TEXT_GETIMEI,"",&font20,0xffffff),
STATIC_IMAGE(170,138,220,220,IDC_STATIC_IMAGE_IMEI,0),
STATIC_IMAGE(633,138,220,220,IDC_STATIC_IMAGE_APP_URL,0),
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
// WS_EX_AUTOSECONDARYDC,
WS_EX_NONE,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "FsetQrcode",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formSettingQrcodeProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
.auto_close_time_set = 30,
};
static MyCtrlTitle ctrls_title[] = {
{
IDC_TITLE,
MYTITLE_LEFT_EXIT,
MYTITLE_RIGHT_NULL,
0,0,1024,40,
"二维码",
"",
0xffffff, 0x333333FF,
buttonNotify,
},
{0},
};
static MyCtrlButton ctrls_button[] = {
{IDC_BUTTON_GETIMEI,MYBUTTON_TYPE_TWO_STATE | MYBUTTON_TYPE_TEXT_NULL,"点击获取二维码",200,384,buttonGetImei},
{0},
};
static FormBase* form_base = NULL;
/* ---------------------------------------------------------------------------*/
/**
* @brief updateImeiImage 更新二维码图片
*
* @param reload 1重新加载图片 0不重新加载
*/
/* ---------------------------------------------------------------------------*/
static void updateImeiImage(int reload)
{
if (reload) {
UnloadBitmap(&bmp_imei);
if (LoadBitmap (HDC_SCREEN,&bmp_imei, QRCODE_IMIE)) {
printf ("LoadBitmap(%s)fail.\n",QRCODE_IMIE);
}
}
if (fileexists(QRCODE_IMIE)) {
ShowWindow(GetDlgItem(form_base->hDlg,IDC_BUTTON_GETIMEI),SW_HIDE);
SendMessage(GetDlgItem(form_base->hDlg,IDC_STATIC_IMAGE_IMEI),STM_SETIMAGE,(WPARAM)&bmp_imei,0);
ShowWindow(GetDlgItem(form_base->hDlg,IDC_STATIC_TEXT_IMEI),SW_SHOWNORMAL);
} else {
ShowWindow(GetDlgItem(form_base->hDlg,IDC_BUTTON_GETIMEI),SW_SHOWNORMAL);
ShowWindow(GetDlgItem(form_base->hDlg,IDC_STATIC_TEXT_IMEI),SW_HIDE);
SendMessage(GetDlgItem(form_base->hDlg,IDC_STATIC_IMAGE_IMEI),STM_SETIMAGE,(WPARAM)&bmp_null,0);
}
}
static void updateAppImage(int reload)
{
if (reload) {
UnloadBitmap(&bmp_app_url);
if (LoadBitmap (HDC_SCREEN,&bmp_app_url, QRCODE_IMIE)) {
printf ("LoadBitmap(%s)fail.\n",QRCODE_IMIE);
}
}
if (fileexists(QRCODE_APP)) {
SendMessage(GetDlgItem(form_base->hDlg,IDC_STATIC_IMAGE_APP_URL),STM_SETIMAGE,(WPARAM)&bmp_app_url,0);
} else {
SendMessage(GetDlgItem(form_base->hDlg,IDC_STATIC_IMAGE_APP_URL),STM_SETIMAGE,(WPARAM)&bmp_null,0);
}
}
static void getImeiCallback(int result)
{
if (result) {
updateImeiImage(1);
SendMessage(GetDlgItem(form_base->hDlg,IDC_STATIC_TEXT_GETIMEI),
MSG_SETTEXT,0,(LPARAM)"机身码获取成功!");
} else {
SendMessage(GetDlgItem(form_base->hDlg,IDC_STATIC_TEXT_GETIMEI),
MSG_SETTEXT,0,(LPARAM)"机身码获取失败!");
}
}
static void buttonGetImei(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
flag_timer_stop = 1;
protocol->getImei(getImeiCallback);
SendMessage(GetDlgItem(GetParent(hwnd),IDC_STATIC_TEXT_GETIMEI),
MSG_SETTEXT,0,(LPARAM)"正在获取机身码,请稍后...");
}
static void enableAutoClose(void)
{
Screen.setCurrent(form_base_priv.name);
flag_timer_stop = 0;
}
/* ----------------------------------------------------------------*/
/**
* @brief buttonNotify 退出按钮
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ----------------------------------------------------------------*/
static void buttonNotify(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc == MYTITLE_BUTTON_EXIT)
ShowWindow(GetParent(hwnd),SW_HIDE);
}
void formSettingQrcodeLoadBmp(void)
{
if (bmp_load_finished == 1)
return;
printf("[%s]\n", __FUNCTION__);
bmpsLoad(bmp_load);
my_button->bmpsLoad(ctrls_button,BMP_LOCAL_PATH);
bmp_load_finished = 1;
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_title[i].idc != 0; i++) {
ctrls_title[i].font = font20;
createMyTitle(hDlg,&ctrls_title[i]);
}
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
createMyButton(hDlg,&ctrls_button[i]);
}
updateImeiImage(0);
updateAppImage(0);
}
/* ----------------------------------------------------------------*/
/**
* @brief formSettingQrcodeProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ----------------------------------------------------------------*/
static int formSettingQrcodeProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
switch(message) // 自定义消息
{
case MSG_TIMER:
{
if (flag_timer_stop)
return 0;
} break;
case MSG_SHOWWINDOW:
{
if (wParam == SW_HIDE) {
UnloadBitmap(&bmp_app_url);
UnloadBitmap(&bmp_imei);
}
} break;
case MSG_ENABLE_WINDOW:
enableAutoClose();
break;
case MSG_DISABLE_WINDOW:
flag_timer_stop = 1;
break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormSettingQrcode(HWND hMainWnd,void (*callback)(void))
{
HWND Form = Screen.Find(form_base_priv.name);
if (fileexists(QRCODE_APP)) {
if (LoadBitmap (HDC_SCREEN,&bmp_app_url, QRCODE_APP)) {
printf ("LoadBitmap(%s)fail.\n",QRCODE_APP);
}
}
if (fileexists(QRCODE_IMIE)) {
if (LoadBitmap (HDC_SCREEN,&bmp_imei, QRCODE_IMIE)) {
printf ("LoadBitmap(%s)fail.\n",QRCODE_IMIE);
}
}
if(Form) {
Screen.setCurrent(form_base_priv.name);
ShowWindow(Form,SW_SHOWNORMAL);
} else {
if (bmp_load_finished == 0) {
return 0;
}
form_base_priv.callBack = callback;
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
<file_sep>/src/app/video/buffer/camerabuf.h
#ifndef _CAMERA_BUF_H_
#define _CAMERA_BUF_H_
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <ion/ion.h>
#include <list>
#include <CameraHal/CameraBuffer.h>
class RKCameraBuffer : public CameraBuffer {
friend class RKCameraBufferAllocator;
public:
std::list<shared_ptr<RKCameraBuffer>> camhals;
virtual void* getHandle(void) const;
virtual void* getPhyAddr(void) const;
virtual void* getVirtAddr(void) const;
virtual const char* getFormat(void);
virtual unsigned int getWidth(void);
virtual unsigned int getHeight(void);
virtual size_t getDataSize(void) const;
virtual void setDataSize(size_t size);
virtual size_t getCapacity(void) const;
virtual unsigned int getStride(void) const;
virtual bool lock(unsigned int usage = CameraBuffer::READ);
virtual bool unlock(unsigned int usage = CameraBuffer::READ);
virtual ~RKCameraBuffer();
virtual int getFd() { return mShareFd;}
protected:
RKCameraBuffer(ion_user_handle_t handle, int sharefd, unsigned long phy, void* vaddr,
const char* camPixFmt, unsigned int width, unsigned int height, int stride, size_t size,
std::weak_ptr<CameraBufferAllocator> allocator, std::weak_ptr<ICameraBufferOwener> bufOwener);
ion_user_handle_t mHandle;
int mShareFd;
void* mVaddr;
unsigned int mWidth;
unsigned int mHeight;
size_t mBufferSize;
const char* mCamPixFmt;
unsigned int mStride;
size_t mDataSize;
unsigned long mPhy;
};
class RKCameraBufferAllocator : public CameraBufferAllocator {
friend class RKCameraBuffer;
public:
RKCameraBufferAllocator(void);
virtual ~RKCameraBufferAllocator(void);
virtual std::shared_ptr<CameraBuffer> alloc(const char* camPixFmt, unsigned int width, unsigned int height,
unsigned int usage, weak_ptr<ICameraBufferOwener> bufOwener) override;
virtual void free(CameraBuffer* buffer) override;
private:
int mIonClient;
};
#endif // FACE_CAMERA_BUFFER_H
<file_sep>/src/app/my_audio.c
/*
* =============================================================================
*
* Filename: my_audio.c
*
* Description: 播放相关音频
*
* Version: 1.0
* Created: 2019-06-27 13:26:10
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "playwav.h"
#include "config.h"
#include "my_mixer.h"
#include "externfunc.h"
#include "my_gpio.h"
#include "thread_helper.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static int loop_start = 0;
static int loop_end = 1;
/* ---------------------------------------------------------------------------*/
/**
* @brief isNeedToPlay 判断是否在免扰时候可以播放音频
*
* @returns 0 不播放 1播放
*/
/* ---------------------------------------------------------------------------*/
int isNeedToPlay(void)
{
if (g_config.mute.state == 0) {
return 1;
}
struct tm *tm = getTime();
int time_now = tm->tm_hour * 60 + tm->tm_min;
if (g_config.mute.start_time <= g_config.mute.end_time) {
if (time_now >= g_config.mute.start_time && time_now <= g_config.mute.end_time)
return 0;
else
return 1;
} else {
if (time_now <= g_config.mute.end_time)
return 0;
if (time_now >= g_config.mute.start_time)
return 0;
return 1;
}
}
void myAudioStopPlay(void)
{
loop_start = 0;
excuteCmd("busybox","killall","aplay",NULL);
}
void myAudioPlayRecognizer(char *usr_name)
{
if (isNeedToPlay() == 0)
return;
char path[64];
gpioTalkDirIn();
sprintf(path,"%s%s.wav",AUDIO_PATH,usr_name);
playwavfile(path);
}
static void* loopPlay(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
char *path = (char *)arg;
if (my_mixer)
my_mixer->SetVolumeEx(my_mixer,g_config.ring_volume);
loop_end = 0;
while (loop_start){
playwavfile(path);
sleep(1);
}
if (path)
free(path);
loop_end = 1;
return NULL;
}
void myAudioPlayRing(void)
{
if (isNeedToPlay() == 0)
return;
if (loop_start == 1)
return;
while (loop_end == 0) {
usleep(1000);
}
loop_start = 1;
gpioTalkDirIn();
char *path = (char *) calloc(1,64);
sprintf(path,"%sring%d.wav",AUDIO_PATH,g_config.ring_num);
createThread(loopPlay,path);
}
static void* oncePlay(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
char *path = (char *)arg;
if (my_mixer)
my_mixer->SetVolumeEx(my_mixer,g_config.ring_volume);
playwavfile(path);
if (path)
free(path);
return NULL;
}
void myAudioPlayRingOnce(void)
{
if (isNeedToPlay() == 0)
return;
char *path = (char *) calloc(1,64);
myAudioStopPlay();
gpioTalkDirIn();
sprintf(path,"%sring%d.wav",AUDIO_PATH,g_config.ring_num);
createThread(oncePlay,path);
}
void myAudioPlayAlarm(void)
{
if (my_mixer)
my_mixer->SetVolumeEx(my_mixer,g_config.alarm_volume);
char path[64];
gpioTalkDirOut();
sprintf(path,"%salarm.wav",AUDIO_PATH);
playwavfile(path);
}
void myAudioPlayDindong(void)
{
gpioTalkDirIn();
excuteCmd("busybox","killall","aplay",NULL);
excuteCmd("/data/play.sh","/data/dingdong.wav",NULL);
}
<file_sep>/src/wireless/iwlist.c
/*
* Wireless Tools
*
* <NAME> - HPLB '99 - HPL 99->07
*
* This tool can access various piece of information on the card
* not part of iwconfig...
* You need to link this code against "iwlist.c" and "-lm".
*
* This file is released under the GPL license.
* Copyright (c) 1997-2007 <NAME> <<EMAIL>>
*/
#include "iwlib.h" /* Header */
#include <sys/time.h>
#include <string.h>
#include "config.h"
/****************************** TYPES ******************************/
/*
* Scan state and meta-information, used to decode events...
*/
typedef struct iwscan_state
{
/* State */
int ap_num; /* Access Point number 1->N */
int val_index; /* Value in table 0->(N-1) */
} iwscan_state;
/*
* Bit to name mapping
*/
typedef struct iwmask_name
{
unsigned int mask; /* bit mask for the value */
const char * name; /* human readable name for the value */
} iwmask_name;
/*
* Types of authentication parameters
*/
typedef struct iw_auth_descr
{
int value; /* Type of auth value */
const char * label; /* User readable version */
const struct iwmask_name * names; /* Names for this value */
const int num_names; /* Number of names */
} iw_auth_descr;
/**************************** CONSTANTS ****************************/
#define IW_SCAN_HACK 0x8000
#define IW_EXTKEY_SIZE (sizeof(struct iw_encode_ext) + IW_ENCODING_TOKEN_MAX)
/* ------------------------ WPA CAPA NAMES ------------------------ */
/*
* This is the user readable name of a bunch of WPA constants in wireless.h
* Maybe this should go in iwlib.c ?
*/
#ifndef WE_ESSENTIAL
#define IW_ARRAY_LEN(x) (sizeof(x)/sizeof((x)[0]))
//static const struct iwmask_name iw_enc_mode_name[] = {
// { IW_ENCODE_RESTRICTED, "restricted" },
// { IW_ENCODE_OPEN, "open" },
//};
//#define IW_ENC_MODE_NUM IW_ARRAY_LEN(iw_enc_mode_name)
static const struct iwmask_name iw_auth_capa_name[] = {
{ IW_ENC_CAPA_WPA, "WPA" },
{ IW_ENC_CAPA_WPA2, "WPA2" },
{ IW_ENC_CAPA_CIPHER_TKIP, "CIPHER-TKIP" },
{ IW_ENC_CAPA_CIPHER_CCMP, "CIPHER-CCMP" },
};
#define IW_AUTH_CAPA_NUM IW_ARRAY_LEN(iw_auth_capa_name)
static const struct iwmask_name iw_auth_cypher_name[] = {
{ IW_AUTH_CIPHER_NONE, "none" },
{ IW_AUTH_CIPHER_WEP40, "WEP-40" },
{ IW_AUTH_CIPHER_TKIP, "TKIP" },
{ IW_AUTH_CIPHER_CCMP, "CCMP" },
{ IW_AUTH_CIPHER_WEP104, "WEP-104" },
};
#define IW_AUTH_CYPHER_NUM IW_ARRAY_LEN(iw_auth_cypher_name)
static const struct iwmask_name iw_wpa_ver_name[] = {
{ IW_AUTH_WPA_VERSION_DISABLED, "disabled" },
{ IW_AUTH_WPA_VERSION_WPA, "WPA" },
{ IW_AUTH_WPA_VERSION_WPA2, "WPA2" },
};
#define IW_WPA_VER_NUM IW_ARRAY_LEN(iw_wpa_ver_name)
static const struct iwmask_name iw_auth_key_mgmt_name[] = {
{ IW_AUTH_KEY_MGMT_802_1X, "802.1x" },
{ IW_AUTH_KEY_MGMT_PSK, "PSK" },
};
#define IW_AUTH_KEY_MGMT_NUM IW_ARRAY_LEN(iw_auth_key_mgmt_name)
static const struct iwmask_name iw_auth_alg_name[] = {
{ IW_AUTH_ALG_OPEN_SYSTEM, "open" },
{ IW_AUTH_ALG_SHARED_KEY, "shared-key" },
{ IW_AUTH_ALG_LEAP, "LEAP" },
};
#define IW_AUTH_ALG_NUM IW_ARRAY_LEN(iw_auth_alg_name)
static const struct iw_auth_descr iw_auth_settings[] = {
{ IW_AUTH_WPA_VERSION, "WPA version", iw_wpa_ver_name, IW_WPA_VER_NUM },
{ IW_AUTH_KEY_MGMT, "Key management", iw_auth_key_mgmt_name, IW_AUTH_KEY_MGMT_NUM },
{ IW_AUTH_CIPHER_PAIRWISE, "Pairwise cipher", iw_auth_cypher_name, IW_AUTH_CYPHER_NUM },
{ IW_AUTH_CIPHER_GROUP, "Pairwise cipher", iw_auth_cypher_name, IW_AUTH_CYPHER_NUM },
{ IW_AUTH_TKIP_COUNTERMEASURES, "TKIP countermeasures", NULL, 0 },
{ IW_AUTH_DROP_UNENCRYPTED, "Drop unencrypted", NULL, 0 },
{ IW_AUTH_80211_AUTH_ALG, "Authentication algorithm", iw_auth_alg_name, IW_AUTH_ALG_NUM },
{ IW_AUTH_RX_UNENCRYPTED_EAPOL, "Receive unencrypted EAPOL", NULL, 0 },
{ IW_AUTH_ROAMING_CONTROL, "Roaming control", NULL, 0 },
{ IW_AUTH_PRIVACY_INVOKED, "Privacy invoked", NULL, 0 },
};
#define IW_AUTH_SETTINGS_NUM IW_ARRAY_LEN(iw_auth_settings)
/* Values for the IW_ENCODE_ALG_* returned by SIOCSIWENCODEEXT */
static const char * iw_encode_alg_name[] = {
"none",
"WEP",
"TKIP",
"CCMP",
"unknown"
};
#define IW_ENCODE_ALG_NUM IW_ARRAY_LEN(iw_encode_alg_name)
#ifndef IW_IE_CIPHER_NONE
/* Cypher values in GENIE (pairwise and group) */
#define IW_IE_CIPHER_NONE 0
#define IW_IE_CIPHER_WEP40 1
#define IW_IE_CIPHER_TKIP 2
#define IW_IE_CIPHER_WRAP 3
#define IW_IE_CIPHER_CCMP 4
#define IW_IE_CIPHER_WEP104 5
/* Key management in GENIE */
#define IW_IE_KEY_MGMT_NONE 0
#define IW_IE_KEY_MGMT_802_1X 1
#define IW_IE_KEY_MGMT_PSK 2
#endif /* IW_IE_CIPHER_NONE */
/* Values for the IW_IE_CIPHER_* in GENIE */
static const char * iw_ie_cypher_name[] = {
"none",
"WEP-40",
"TKIP",
"WRAP",
"CCMP",
"WEP-104",
};
#define IW_IE_CYPHER_NUM IW_ARRAY_LEN(iw_ie_cypher_name)
/* Values for the IW_IE_KEY_MGMT_* in GENIE */
static const char * iw_ie_key_mgmt_name[] = {
"none",
"802.1x",
"PSK",
};
#define IW_IE_KEY_MGMT_NUM IW_ARRAY_LEN(iw_ie_key_mgmt_name)
#endif /* WE_ESSENTIAL */
static TcWifiScan *g_ap_info;
static int *g_ap_cnt = NULL;
/************************* WPA SUBROUTINES *************************/
#ifndef WE_ESSENTIAL
/*------------------------------------------------------------------*/
/*
* Print all names corresponding to a mask.
* This may want to be used in iw_print_retry_value() ?
*/
static void
iw_print_mask_name(unsigned int mask,
const struct iwmask_name names[],
const unsigned int num_names,
const char * sep)
{
unsigned int i;
/* Print out all names for the bitmask */
for(i = 0; i < num_names; i++)
{
if(mask & names[i].mask)
{
/* Print out */
printf("%s%s", sep, names[i].name);
/* Remove the bit from the mask */
mask &= ~names[i].mask;
}
}
/* If there is unconsumed bits... */
if(mask != 0)
printf("%sUnknown", sep);
}
/*------------------------------------------------------------------*/
/*
* Print the name corresponding to a value, with overflow check.
*/
static void
iw_print_value_name(unsigned int value,
const char * names[],
const unsigned int num_names)
{
#ifdef TC_DEBUG
if(value >= num_names)
printf(" unknown (%d)", value);
else
printf(" %s", names[value]);
#endif
}
/*------------------------------------------------------------------*/
/*
* Parse, and display the results of an unknown IE.
*
*/
static void
iw_print_ie_unknown(unsigned char * iebuf,
int buflen)
{
int ielen = iebuf[1] + 2;
int i;
if(ielen > buflen)
ielen = buflen;
#ifdef DEBUG
printf("Unknown: ");
for(i = 0; i < ielen; i++)
printf("%02X", iebuf[i]);
printf("\n");
#endif
}
/*------------------------------------------------------------------*/
/*
* Parse, and display the results of a WPA or WPA2 IE.
*
*/
static inline void
iw_print_ie_wpa(unsigned char * iebuf,
int buflen)
{
int ielen = iebuf[1] + 2;
int offset = 2; /* Skip the IE id, and the length. */
unsigned char wpa1_oui[3] = {0x00, 0x50, 0xf2};
unsigned char wpa2_oui[3] = {0x00, 0x0f, 0xac};
unsigned char * wpa_oui;
int i;
uint16_t ver = 0;
uint16_t cnt = 0;
if(ielen > buflen)
ielen = buflen;
#ifdef DEBUG
/* Debugging code. In theory useless, because it's debugged ;-) */
printf("IE raw value %d [%02X", buflen, iebuf[0]);
for(i = 1; i < buflen; i++)
printf(":%02X", iebuf[i]);
printf("]\n");
#endif
switch(iebuf[0])
{
case 0x30: /* WPA2 */
/* Check if we have enough data */
if(ielen < 4)
{
iw_print_ie_unknown(iebuf, buflen);
return;
}
wpa_oui = wpa2_oui;
break;
case 0xdd: /* WPA or else */
wpa_oui = wpa1_oui;
/* Not all IEs that start with 0xdd are WPA.
* So check that the OUI is valid. Note : offset==2 */
if((ielen < 8)
|| (memcmp(&iebuf[offset], wpa_oui, 3) != 0)
|| (iebuf[offset + 3] != 0x01))
{
iw_print_ie_unknown(iebuf, buflen);
return;
}
/* Skip the OUI type */
offset += 4;
break;
default:
return;
}
/* Pick version number (little endian) */
ver = iebuf[offset] | (iebuf[offset + 1] << 8);
offset += 2;
if(iebuf[0] == 0xdd) {
(g_ap_info + (*g_ap_cnt) - 1)->auth |= TC_AUTH_TYPE_WPAPSK;
#ifdef TC_DEBUG
printf("WPA Version %d\n", ver);
#endif
}
if(iebuf[0] == 0x30) {
(g_ap_info + (*g_ap_cnt) - 1)->auth |= TC_AUTH_TYPE_WPA2PSK;
#ifdef TC_DEBUG
printf("IEEE 802.11i/WPA2 Version %d\n", ver);
#endif
}
/* From here, everything is technically optional. */
/* Check if we are done */
if(ielen < (offset + 4))
{
/* We have a short IE. So we should assume TKIP/TKIP. */
(g_ap_info + (*g_ap_cnt) - 1)->encry |= AWSS_ENC_TYPE_TKIP;
#ifdef TC_DEBUG
printf(" Group Cipher : TKIP\n");
printf(" Pairwise Cipher : TKIP\n");
#endif
return;
}
/* Next we have our group cipher. */
if(memcmp(&iebuf[offset], wpa_oui, 3) != 0)
{
#ifdef TC_DEBUG
printf(" Group Cipher : Proprietary\n");
#endif
}
else
{
(g_ap_info + (*g_ap_cnt) - 1)->encry = AWSS_ENC_TYPE_AES;
#ifdef TC_DEBUG
printf(" Group Cipher :");
iw_print_value_name(iebuf[offset+3],
iw_ie_cypher_name, IW_IE_CYPHER_NUM);
printf("\n");
#endif
}
offset += 4;
/* Check if we are done */
if(ielen < (offset + 2))
{
/* We don't have a pairwise cipher, or auth method. Assume TKIP. */
printf(" Pairwise Ciphers : TKIP\n");
return;
}
/* Otherwise, we have some number of pairwise ciphers. */
cnt = iebuf[offset] | (iebuf[offset + 1] << 8);
offset += 2;
#ifdef TC_DEBUG
printf(" Pairwise Ciphers (%d) :", cnt);
#endif
if(ielen < (offset + 4*cnt))
return;
for(i = 0; i < cnt; i++)
{
if(memcmp(&iebuf[offset], wpa_oui, 3) != 0)
{
#ifdef TC_DEBUG
printf(" Proprietary");
#endif
}
else
{
iw_print_value_name(iebuf[offset+3],
iw_ie_cypher_name, IW_IE_CYPHER_NUM);
}
offset+=4;
}
#ifdef TC_DEBUG
printf("\n");
#endif
/* Check if we are done */
if(ielen < (offset + 2))
return;
/* Now, we have authentication suites. */
cnt = iebuf[offset] | (iebuf[offset + 1] << 8);
offset += 2;
#ifdef TC_DEBUG
printf(" Authentication Suites (%d) :", cnt);
#endif
if(ielen < (offset + 4*cnt))
return;
for(i = 0; i < cnt; i++)
{
if(memcmp(&iebuf[offset], wpa_oui, 3) != 0)
{
printf(" Proprietary");
}
else
{
iw_print_value_name(iebuf[offset+3],
iw_ie_key_mgmt_name, IW_IE_KEY_MGMT_NUM);
}
offset+=4;
}
#ifdef TC_DEBUG
printf("\n");
#endif
/* Check if we are done */
if(ielen < (offset + 1))
return;
/* Otherwise, we have capabilities bytes.
* For now, we only care about preauth which is in bit position 1 of the
* first byte. (But, preauth with WPA version 1 isn't supposed to be
* allowed.) 8-) */
if(iebuf[offset] & 0x01)
{
printf(" Preauthentication Supported\n");
}
}
/*------------------------------------------------------------------*/
/*
* Process a generic IE and display the info in human readable form
* for some of the most interesting ones.
* For now, we only decode the WPA IEs.
*/
static inline void
iw_print_gen_ie(unsigned char * buffer,
int buflen)
{
int offset = 0;
/* Loop on each IE, each IE is minimum 2 bytes */
while(offset <= (buflen - 2))
{
#ifdef TC_DEBUG
printf(" IE: ");
#endif
/* Check IE type */
switch(buffer[offset])
{
case 0xdd: /* WPA1 (and other) */
case 0x30: /* WPA2 */
iw_print_ie_wpa(buffer + offset, buflen);
break;
default:
iw_print_ie_unknown(buffer + offset, buflen);
}
/* Skip over this IE to the next one in the list. */
offset += buffer[offset+1] + 2;
}
}
#endif /* WE_ESSENTIAL */
/***************************** SCANNING *****************************/
/*
* This one behave quite differently from the others
*
* Note that we don't use the scanning capability of iwlib (functions
* iw_process_scan() and iw_scan()). The main reason is that
* iw_process_scan() return only a subset of the scan data to the caller,
* for example custom elements and bitrates are ommited. Here, we
* do the complete job...
*/
/*------------------------------------------------------------------*/
/*
* Print one element from the scanning results
*/
static inline void
print_scanning_token(struct stream_descr * stream, /* Stream of events */
struct iw_event * event, /* Extracted token */
struct iwscan_state * state,
struct iw_range * iw_range, /* Range info */
int has_range)
{
char buffer[128]; /* Temporary buffer */
/* Now, let's decode the event */
switch(event->cmd)
{
case SIOCGIWAP:
{
const struct sockaddr *sap;
const struct ether_addr * eth;
sap = &event->u.ap_addr;
eth = (const struct ether_addr *) sap->sa_data;
#ifdef DEBUG
printf(" Cell %02d - Address: %s\n", state->ap_num,
iw_saether_ntop(&event->u.ap_addr, buffer));
#endif
(g_ap_info + (*g_ap_cnt) - 1)->bssid[0] |= eth->ether_addr_octet[0];
(g_ap_info + (*g_ap_cnt) - 1)->bssid[1] |= eth->ether_addr_octet[1];
(g_ap_info + (*g_ap_cnt) - 1)->bssid[2] |= eth->ether_addr_octet[2];
(g_ap_info + (*g_ap_cnt) - 1)->bssid[3] |= eth->ether_addr_octet[3];
(g_ap_info + (*g_ap_cnt) - 1)->bssid[4] |= eth->ether_addr_octet[4];
(g_ap_info + (*g_ap_cnt) - 1)->bssid[5] |= eth->ether_addr_octet[5];
if (*g_ap_cnt < 99)
(*g_ap_cnt)++;
state->ap_num++;
}
break;
case SIOCGIWNWID:
#ifdef TC_DEBUG
if(event->u.nwid.disabled)
printf(" NWID:off/any\n");
else
printf(" NWID:%X\n", event->u.nwid.value);
#endif
break;
case SIOCGIWFREQ:
{
double freq; /* Frequency/channel */
int channel = -1; /* Converted to channel */
freq = iw_freq2float(&(event->u.freq));
/* Convert to channel if possible */
if(has_range)
channel = iw_freq_to_channel(freq, iw_range);
#ifdef TC_DEBUG
iw_print_freq(buffer, sizeof(buffer),
freq, channel, event->u.freq.flags);
printf(" %s\n", buffer);
#endif
(g_ap_info + (*g_ap_cnt) - 1)->channel = channel;
}
break;
case SIOCGIWMODE:
/* Note : event->u.mode is unsigned, no need to check <= 0 */
#ifdef TC_DEBUG
if(event->u.mode >= IW_NUM_OPER_MODE)
event->u.mode = IW_NUM_OPER_MODE;
printf(" Mode:%s\n",
iw_operation_mode[event->u.mode]);
#endif
break;
case SIOCGIWNAME:
#ifdef TC_DEBUG
printf(" Protocol:%-1.16s\n", event->u.name);
#endif
break;
case SIOCGIWESSID:
{
memset((g_ap_info + (*g_ap_cnt) - 1)->ssid, '\0', sizeof((g_ap_info + (*g_ap_cnt) - 1)->ssid));
if((event->u.essid.pointer) && (event->u.essid.length))
memcpy((g_ap_info + (*g_ap_cnt) - 1)->ssid, event->u.essid.pointer, event->u.essid.length);
#ifdef TC_DEBUG
char essid[IW_ESSID_MAX_SIZE+1] = {0};
if((event->u.essid.pointer) && (event->u.essid.length))
memcpy(essid, event->u.essid.pointer, event->u.essid.length);
if(event->u.essid.flags)
{
// [> Does it have an ESSID index ? <]
if((event->u.essid.flags & IW_ENCODE_INDEX) > 1)
printf(" ESSID:\"%s\" [%d]\n", essid,
(event->u.essid.flags & IW_ENCODE_INDEX));
else
printf(" ESSID:\"%s\"\n", essid);
}
else
printf(" ESSID:off/any/hidden\n");
#endif
}
break;
case SIOCGIWENCODE:
{
#ifdef TC_DEBUG
unsigned char key[IW_ENCODING_TOKEN_MAX];
if(event->u.data.pointer)
memcpy(key, event->u.data.pointer, event->u.data.length);
else
event->u.data.flags |= IW_ENCODE_NOKEY;
printf(" Encryption key:");
if(event->u.data.flags & IW_ENCODE_DISABLED)
printf("off\n");
else
{
/* Display the key */
iw_print_key(buffer, sizeof(buffer), key, event->u.data.length,
event->u.data.flags);
printf("%s", buffer);
/* Other info... */
if((event->u.data.flags & IW_ENCODE_INDEX) > 1)
printf(" [%d]", event->u.data.flags & IW_ENCODE_INDEX);
if(event->u.data.flags & IW_ENCODE_RESTRICTED)
printf(" Security mode:restricted");
if(event->u.data.flags & IW_ENCODE_OPEN)
printf(" Security mode:open");
printf("\n");
}
#endif
}
break;
case SIOCGIWRATE:
#ifdef TC_DEBUG
if(state->val_index == 0)
printf(" Bit Rates:");
else
if((state->val_index % 5) == 0)
printf("\n ");
else
printf("; ");
iw_print_bitrate(buffer, sizeof(buffer), event->u.bitrate.value);
printf("%s", buffer);
#endif
/* Check for termination */
if(stream->value == NULL)
{
#ifdef TC_DEBUG
printf("\n");
#endif
state->val_index = 0;
}
else
state->val_index++;
break;
case SIOCGIWMODUL:
{
#ifdef TC_DEBUG
unsigned int modul = event->u.param.value;
int i;
int n = 0;
printf(" Modulations :");
for(i = 0; i < IW_SIZE_MODUL_LIST; i++)
{
if((modul & iw_modul_list[i].mask) == iw_modul_list[i].mask)
{
if((n++ % 8) == 7)
printf("\n ");
else
printf(" ; ");
printf("%s", iw_modul_list[i].cmd);
}
}
printf("\n");
#endif
}
break;
case IWEVQUAL:
{
iwqual * qual = &event->u.qual;
if(has_range && ((qual->level != 0)
|| (qual->updated & (IW_QUAL_DBM | IW_QUAL_RCPI))))
{
if(!(qual->updated & IW_QUAL_QUAL_INVALID)) {
(g_ap_info + (*g_ap_cnt) - 1)->rssi = qual->qual;
}
}
if (((g_ap_info + (*g_ap_cnt) - 1)->auth & TC_AUTH_TYPE_WPA2PSK )
&& ((g_ap_info + (*g_ap_cnt) - 1)->auth & TC_AUTH_TYPE_WPAPSK) ) {
(g_ap_info + (*g_ap_cnt) - 1)->auth = AWSS_AUTH_TYPE_WPAPSKWPA2PSK;
} else if ((g_ap_info + (*g_ap_cnt) - 1)->auth & TC_AUTH_TYPE_WPA2PSK) {
(g_ap_info + (*g_ap_cnt) - 1)->auth = AWSS_AUTH_TYPE_WPA2PSK;
} else if ((g_ap_info + (*g_ap_cnt) - 1)->auth & TC_AUTH_TYPE_WPAPSK) {
(g_ap_info + (*g_ap_cnt) - 1)->auth = AWSS_AUTH_TYPE_WPAPSK;
}
#ifdef TC_DEBUG
iw_print_stats(buffer, sizeof(buffer),
&event->u.qual, iw_range, has_range);
printf(" %s\n", buffer);
#endif
}
break;
#ifndef WE_ESSENTIAL
case IWEVGENIE:
/* Informations Elements are complex, let's do only some of them */
iw_print_gen_ie(event->u.data.pointer, event->u.data.length);
break;
#endif /* WE_ESSENTIAL */
case IWEVCUSTOM:
{
#ifdef TC_DEBUG
char custom[IW_CUSTOM_MAX+1];
if((event->u.data.pointer) && (event->u.data.length))
memcpy(custom, event->u.data.pointer, event->u.data.length);
custom[event->u.data.length] = '\0';
printf(" Extra:%s\n", custom);
#endif
}
break;
default:
printf(" (Unknown Wireless Token 0x%04X)\n",
event->cmd);
} /* switch(event->cmd) */
}
/*------------------------------------------------------------------*/
/*
* Perform a scanning on one device
*/
static int
print_scanning_info(int skfd,
char * ifname,
char * args[], /* Command line args */
int count) /* Args count */
{
struct iwreq wrq;
struct iw_scan_req scanopt; /* Options for 'set' */
int scanflags = 0; /* Flags for scan */
unsigned char * buffer = NULL; /* Results */
int buflen = IW_SCAN_MAX_DATA; /* Min for compat WE<17 */
struct iw_range range;
int has_range;
struct timeval tv; /* Select timeout */
int timeout = 15000000; /* 15s */
/* Avoid "Unused parameter" warning */
args = args; count = count;
/* Debugging stuff */
if((IW_EV_LCP_PK2_LEN != IW_EV_LCP_PK_LEN) || (IW_EV_POINT_PK2_LEN != IW_EV_POINT_PK_LEN))
{
fprintf(stderr, "*** Please report to <EMAIL> your platform details\n");
fprintf(stderr, "*** and the following line :\n");
fprintf(stderr, "*** IW_EV_LCP_PK2_LEN = %zu ; IW_EV_POINT_PK2_LEN = %zu\n\n",
IW_EV_LCP_PK2_LEN, IW_EV_POINT_PK2_LEN);
}
/* Get range stuff */
has_range = (iw_get_range_info(skfd, ifname, &range) >= 0);
/* Check if the interface could support scanning. */
if((!has_range) || (range.we_version_compiled < 14))
{
fprintf(stderr, "%-8.16s Interface doesn't support scanning.\n\n",
ifname);
return(-1);
}
/* Init timeout value -> 250ms between set and first get */
tv.tv_sec = 0;
tv.tv_usec = 250000;
/* Clean up set args */
memset(&scanopt, 0, sizeof(scanopt));
/* Parse command line arguments and extract options.
* Note : when we have enough options, we should use the parser
* from iwconfig... */
while(count > 0)
{
/* One arg is consumed (the option name) */
count--;
/*
* Check for Active Scan (scan with specific essid)
*/
if(!strncmp(args[0], "essid", 5))
{
if(count < 1)
{
fprintf(stderr, "Too few arguments for scanning option [%s]\n",
args[0]);
return(-1);
}
args++;
count--;
/* Store the ESSID in the scan options */
scanopt.essid_len = strlen(args[0]);
memcpy(scanopt.essid, args[0], scanopt.essid_len);
/* Initialise BSSID as needed */
if(scanopt.bssid.sa_family == 0)
{
scanopt.bssid.sa_family = ARPHRD_ETHER;
memset(scanopt.bssid.sa_data, 0xff, ETH_ALEN);
}
/* Scan only this ESSID */
scanflags |= IW_SCAN_THIS_ESSID;
}
else
/* Check for last scan result (do not trigger scan) */
if(!strncmp(args[0], "last", 4))
{
/* Hack */
scanflags |= IW_SCAN_HACK;
}
else
{
fprintf(stderr, "Invalid scanning option [%s]\n", args[0]);
return(-1);
}
/* Next arg */
args++;
}
/* Check if we have scan options */
if(scanflags)
{
wrq.u.data.pointer = (caddr_t) &scanopt;
wrq.u.data.length = sizeof(scanopt);
wrq.u.data.flags = scanflags;
}
else
{
wrq.u.data.pointer = NULL;
wrq.u.data.flags = 0;
wrq.u.data.length = 0;
}
/* If only 'last' was specified on command line, don't trigger a scan */
if(scanflags == IW_SCAN_HACK)
{
/* Skip waiting */
tv.tv_usec = 0;
}
else
{
/* Initiate Scanning */
if(iw_set_ext(skfd, ifname, SIOCSIWSCAN, &wrq) < 0)
{
if((errno != EPERM) || (scanflags != 0))
{
fprintf(stderr, "%-8.16s Interface doesn't support scanning : %s\n\n",
ifname, strerror(errno));
return(-1);
}
/* If we don't have the permission to initiate the scan, we may
* still have permission to read left-over results.
* But, don't wait !!! */
#if 0
/* Not cool, it display for non wireless interfaces... */
fprintf(stderr, "%-8.16s (Could not trigger scanning, just reading left-over results)\n", ifname);
#endif
tv.tv_usec = 0;
}
}
timeout -= tv.tv_usec;
/* Forever */
while(1)
{
fd_set rfds; /* File descriptors for select */
int last_fd; /* Last fd */
int ret;
/* Guess what ? We must re-generate rfds each time */
FD_ZERO(&rfds);
last_fd = -1;
/* In here, add the rtnetlink fd in the list */
/* Wait until something happens */
ret = select(last_fd + 1, &rfds, NULL, NULL, &tv);
/* Check if there was an error */
if(ret < 0)
{
if(errno == EAGAIN || errno == EINTR)
continue;
fprintf(stderr, "Unhandled signal - exiting...\n");
return(-1);
}
/* Check if there was a timeout */
if(ret == 0)
{
unsigned char * newbuf;
realloc:
/* (Re)allocate the buffer - realloc(NULL, len) == malloc(len) */
newbuf = realloc(buffer, buflen);
if(newbuf == NULL)
{
if(buffer)
free(buffer);
fprintf(stderr, "%s: Allocation failed\n", __FUNCTION__);
return(-1);
}
buffer = newbuf;
/* Try to read the results */
wrq.u.data.pointer = buffer;
wrq.u.data.flags = 0;
wrq.u.data.length = buflen;
if(iw_get_ext(skfd, ifname, SIOCGIWSCAN, &wrq) < 0)
{
/* Check if buffer was too small (WE-17 only) */
if((errno == E2BIG) && (range.we_version_compiled > 16))
{
/* Some driver may return very large scan results, either
* because there are many cells, or because they have many
* large elements in cells (like IWEVCUSTOM). Most will
* only need the regular sized buffer. We now use a dynamic
* allocation of the buffer to satisfy everybody. Of course,
* as we don't know in advance the size of the array, we try
* various increasing sizes. Jean II */
/* Check if the driver gave us any hints. */
if(wrq.u.data.length > buflen)
buflen = wrq.u.data.length;
else
buflen *= 2;
/* Try again */
goto realloc;
}
/* Check if results not available yet */
if(errno == EAGAIN)
{
/* Restart timer for only 100ms*/
tv.tv_sec = 0;
tv.tv_usec = 100000;
timeout -= tv.tv_usec;
if(timeout > 0)
continue; /* Try again later */
}
/* Bad error */
free(buffer);
fprintf(stderr, "%-8.16s Failed to read scan data : %s\n\n",
ifname, strerror(errno));
return(-2);
}
else
/* We have the results, go to process them */
break;
}
/* In here, check if event and event type
* if scan event, read results. All errors bad & no reset timeout */
}
if(wrq.u.data.length)
{
struct iw_event iwe;
struct stream_descr stream;
struct iwscan_state state = { .ap_num = 1, .val_index = 0 };
int ret;
#ifdef DEBUG
/* Debugging code. In theory useless, because it's debugged ;-) */
int i;
printf("Scan result %d [%02X", wrq.u.data.length, buffer[0]);
for(i = 1; i < wrq.u.data.length; i++)
printf(":%02X", buffer[i]);
printf("]\n");
printf("%-8.16s Scan completed :\n", ifname);
#endif
iw_init_event_stream(&stream, (char *) buffer, wrq.u.data.length);
do
{
/* Extract an event and print it */
ret = iw_extract_event_stream(&stream, &iwe,
range.we_version_compiled);
if(ret > 0) {
print_scanning_token(&stream, &iwe, &state,
&range, has_range);
}
}
while(ret > 0);
printf("\n");
}
else
printf("%-8.16s No scan results\n\n", ifname);
free(buffer);
return(0);
}
/*********************** FREQUENCIES/CHANNELS ***********************/
/*------------------------------------------------------------------*/
/*
* Print the number of channels and available frequency for the device
*/
static int
print_freq_info(int skfd,
char * ifname,
char * args[], /* Command line args */
int count) /* Args count */
{
struct iwreq wrq;
struct iw_range range;
double freq;
int k;
int channel;
char buffer[128]; /* Temporary buffer */
/* Avoid "Unused parameter" warning */
args = args; count = count;
/* Get list of frequencies / channels */
if(iw_get_range_info(skfd, ifname, &range) < 0)
fprintf(stderr, "%-8.16s no frequency information.\n\n",
ifname);
else
{
if(range.num_frequency > 0)
{
printf("%-8.16s %d channels in total; available frequencies :\n",
ifname, range.num_channels);
/* Print them all */
for(k = 0; k < range.num_frequency; k++)
{
freq = iw_freq2float(&(range.freq[k]));
iw_print_freq_value(buffer, sizeof(buffer), freq);
printf(" Channel %.2d : %s\n",
range.freq[k].i, buffer);
}
}
else
printf("%-8.16s %d channels\n",
ifname, range.num_channels);
/* Get current frequency / channel and display it */
if(iw_get_ext(skfd, ifname, SIOCGIWFREQ, &wrq) >= 0)
{
freq = iw_freq2float(&(wrq.u.freq));
channel = iw_freq_to_channel(freq, &range);
iw_print_freq(buffer, sizeof(buffer),
freq, channel, wrq.u.freq.flags);
printf(" Current %s\n\n", buffer);
}
}
return(0);
}
/***************************** BITRATES *****************************/
/*------------------------------------------------------------------*/
/*
* Print the number of available bitrates for the device
*/
static int
print_bitrate_info(int skfd,
char * ifname,
char * args[], /* Command line args */
int count) /* Args count */
{
struct iwreq wrq;
struct iw_range range;
int k;
char buffer[128];
/* Avoid "Unused parameter" warning */
args = args; count = count;
/* Extract range info */
if(iw_get_range_info(skfd, ifname, &range) < 0)
fprintf(stderr, "%-8.16s no bit-rate information.\n\n",
ifname);
else
{
if((range.num_bitrates > 0) && (range.num_bitrates <= IW_MAX_BITRATES))
{
printf("%-8.16s %d available bit-rates :\n",
ifname, range.num_bitrates);
/* Print them all */
for(k = 0; k < range.num_bitrates; k++)
{
iw_print_bitrate(buffer, sizeof(buffer), range.bitrate[k]);
/* Maybe this should be %10s */
printf("\t %s\n", buffer);
}
}
else
printf("%-8.16s unknown bit-rate information.\n", ifname);
/* Get current bit rate */
if(iw_get_ext(skfd, ifname, SIOCGIWRATE, &wrq) >= 0)
{
iw_print_bitrate(buffer, sizeof(buffer), wrq.u.bitrate.value);
printf(" Current Bit Rate%c%s\n",
(wrq.u.bitrate.fixed ? '=' : ':'), buffer);
}
/* Try to get the broadcast bitrate if it exist... */
if(range.bitrate_capa & IW_BITRATE_BROADCAST)
{
wrq.u.bitrate.flags = IW_BITRATE_BROADCAST;
if(iw_get_ext(skfd, ifname, SIOCGIWRATE, &wrq) >= 0)
{
iw_print_bitrate(buffer, sizeof(buffer), wrq.u.bitrate.value);
printf(" Broadcast Bit Rate%c%s\n",
(wrq.u.bitrate.fixed ? '=' : ':'), buffer);
}
}
printf("\n");
}
return(0);
}
/************************* ENCRYPTION KEYS *************************/
/*------------------------------------------------------------------*/
/*
* Print all the available encryption keys for the device
*/
static int
print_keys_info(int skfd,
char * ifname,
char * args[], /* Command line args */
int count) /* Args count */
{
struct iwreq wrq;
struct iw_range range;
unsigned char key[IW_ENCODING_TOKEN_MAX];
unsigned int k;
char buffer[128];
/* Avoid "Unused parameter" warning */
args = args; count = count;
/* Extract range info */
if(iw_get_range_info(skfd, ifname, &range) < 0)
fprintf(stderr, "%-8.16s no encryption keys information.\n\n",
ifname);
else
{
printf("%-8.16s ", ifname);
/* Print key sizes */
if((range.num_encoding_sizes > 0) &&
(range.num_encoding_sizes < IW_MAX_ENCODING_SIZES))
{
printf("%d key sizes : %d", range.num_encoding_sizes,
range.encoding_size[0] * 8);
/* Print them all */
for(k = 1; k < range.num_encoding_sizes; k++)
printf(", %d", range.encoding_size[k] * 8);
printf("bits\n ");
}
/* Print the keys and associate mode */
printf("%d keys available :\n", range.max_encoding_tokens);
for(k = 1; k <= range.max_encoding_tokens; k++)
{
wrq.u.data.pointer = (caddr_t) key;
wrq.u.data.length = IW_ENCODING_TOKEN_MAX;
wrq.u.data.flags = k;
if(iw_get_ext(skfd, ifname, SIOCGIWENCODE, &wrq) < 0)
{
fprintf(stderr, "Error reading wireless keys (SIOCGIWENCODE): %s\n", strerror(errno));
break;
}
if((wrq.u.data.flags & IW_ENCODE_DISABLED) ||
(wrq.u.data.length == 0))
printf("\t\t[%d]: off\n", k);
else
{
/* Display the key */
iw_print_key(buffer, sizeof(buffer),
key, wrq.u.data.length, wrq.u.data.flags);
printf("\t\t[%d]: %s", k, buffer);
/* Other info... */
printf(" (%d bits)", wrq.u.data.length * 8);
printf("\n");
}
}
/* Print current key index and mode */
wrq.u.data.pointer = (caddr_t) key;
wrq.u.data.length = IW_ENCODING_TOKEN_MAX;
wrq.u.data.flags = 0; /* Set index to zero to get current */
if(iw_get_ext(skfd, ifname, SIOCGIWENCODE, &wrq) >= 0)
{
/* Note : if above fails, we have already printed an error
* message int the loop above */
printf(" Current Transmit Key: [%d]\n",
wrq.u.data.flags & IW_ENCODE_INDEX);
if(wrq.u.data.flags & IW_ENCODE_RESTRICTED)
printf(" Security mode:restricted\n");
if(wrq.u.data.flags & IW_ENCODE_OPEN)
printf(" Security mode:open\n");
}
printf("\n\n");
}
return(0);
}
/************************* POWER MANAGEMENT *************************/
/*------------------------------------------------------------------*/
/*
* Print Power Management info for each device
*/
static int
get_pm_value(int skfd,
char * ifname,
struct iwreq * pwrq,
int flags,
char * buffer,
int buflen,
int we_version_compiled)
{
/* Get Another Power Management value */
pwrq->u.power.flags = flags;
if(iw_get_ext(skfd, ifname, SIOCGIWPOWER, pwrq) >= 0)
{
/* Let's check the value and its type */
if(pwrq->u.power.flags & IW_POWER_TYPE)
{
iw_print_pm_value(buffer, buflen,
pwrq->u.power.value, pwrq->u.power.flags,
we_version_compiled);
printf("\n %s", buffer);
}
}
return(pwrq->u.power.flags);
}
/*------------------------------------------------------------------*/
/*
* Print Power Management range for each type
*/
static void
print_pm_value_range(char * name,
int mask,
int iwr_flags,
int iwr_min,
int iwr_max,
char * buffer,
int buflen,
int we_version_compiled)
{
if(iwr_flags & mask)
{
int flags = (iwr_flags & ~(IW_POWER_MIN | IW_POWER_MAX));
/* Display if auto or fixed */
printf("%s %s ; ",
(iwr_flags & IW_POWER_MIN) ? "Auto " : "Fixed",
name);
/* Print the range */
iw_print_pm_value(buffer, buflen,
iwr_min, flags | IW_POWER_MIN,
we_version_compiled);
printf("%s\n ", buffer);
iw_print_pm_value(buffer, buflen,
iwr_max, flags | IW_POWER_MAX,
we_version_compiled);
printf("%s\n ", buffer);
}
}
/*------------------------------------------------------------------*/
/*
* Power Management types of values
*/
static const unsigned int pm_type_flags[] = {
IW_POWER_PERIOD,
IW_POWER_TIMEOUT,
IW_POWER_SAVING,
};
static const int pm_type_flags_size = (sizeof(pm_type_flags)/sizeof(pm_type_flags[0]));
/*------------------------------------------------------------------*/
/*
* Print Power Management info for each device
*/
static int
print_pm_info(int skfd,
char * ifname,
char * args[], /* Command line args */
int count) /* Args count */
{
struct iwreq wrq;
struct iw_range range;
char buffer[128];
/* Avoid "Unused parameter" warning */
args = args; count = count;
/* Extract range info */
if((iw_get_range_info(skfd, ifname, &range) < 0) ||
(range.we_version_compiled < 10))
fprintf(stderr, "%-8.16s no power management information.\n\n",
ifname);
else
{
printf("%-8.16s ", ifname);
/* Display modes availables */
if(range.pm_capa & IW_POWER_MODE)
{
printf("Supported modes :\n ");
if(range.pm_capa & (IW_POWER_UNICAST_R | IW_POWER_MULTICAST_R))
printf("\t\to Receive all packets (unicast & multicast)\n ");
if(range.pm_capa & IW_POWER_UNICAST_R)
printf("\t\to Receive Unicast only (discard multicast)\n ");
if(range.pm_capa & IW_POWER_MULTICAST_R)
printf("\t\to Receive Multicast only (discard unicast)\n ");
if(range.pm_capa & IW_POWER_FORCE_S)
printf("\t\to Force sending using Power Management\n ");
if(range.pm_capa & IW_POWER_REPEATER)
printf("\t\to Repeat multicast\n ");
}
/* Display min/max period availables */
print_pm_value_range("period ", IW_POWER_PERIOD,
range.pmp_flags, range.min_pmp, range.max_pmp,
buffer, sizeof(buffer), range.we_version_compiled);
/* Display min/max timeout availables */
print_pm_value_range("timeout", IW_POWER_TIMEOUT,
range.pmt_flags, range.min_pmt, range.max_pmt,
buffer, sizeof(buffer), range.we_version_compiled);
/* Display min/max saving availables */
print_pm_value_range("saving ", IW_POWER_SAVING,
range.pms_flags, range.min_pms, range.max_pms,
buffer, sizeof(buffer), range.we_version_compiled);
/* Get current Power Management settings */
wrq.u.power.flags = 0;
if(iw_get_ext(skfd, ifname, SIOCGIWPOWER, &wrq) >= 0)
{
int flags = wrq.u.power.flags;
/* Is it disabled ? */
if(wrq.u.power.disabled)
printf("Current mode:off\n");
else
{
unsigned int pm_type = 0;
unsigned int pm_mask = 0;
unsigned int remain_mask = range.pm_capa & IW_POWER_TYPE;
int i = 0;
/* Let's check the mode */
iw_print_pm_mode(buffer, sizeof(buffer), flags);
printf("Current %s", buffer);
/* Let's check if nothing (simply on) */
if((flags & IW_POWER_MODE) == IW_POWER_ON)
printf("mode:on");
/* Let's check the value and its type */
if(wrq.u.power.flags & IW_POWER_TYPE)
{
iw_print_pm_value(buffer, sizeof(buffer),
wrq.u.power.value, wrq.u.power.flags,
range.we_version_compiled);
printf("\n %s", buffer);
}
while(1)
{
/* Deal with min/max for the current value */
pm_mask = 0;
/* If we have been returned a MIN value, ask for the MAX */
if(flags & IW_POWER_MIN)
pm_mask = IW_POWER_MAX;
/* If we have been returned a MAX value, ask for the MIN */
if(flags & IW_POWER_MAX)
pm_mask = IW_POWER_MIN;
/* If we have something to ask for... */
if(pm_mask)
{
pm_mask |= pm_type;
get_pm_value(skfd, ifname, &wrq, pm_mask,
buffer, sizeof(buffer),
range.we_version_compiled);
}
/* Remove current type from mask */
remain_mask &= ~(wrq.u.power.flags);
/* Check what other types we still have to read */
while(i < pm_type_flags_size)
{
pm_type = remain_mask & pm_type_flags[i];
if(pm_type)
break;
i++;
}
/* Nothing anymore : exit the loop */
if(!pm_type)
break;
/* Ask for this other type of value */
flags = get_pm_value(skfd, ifname, &wrq, pm_type,
buffer, sizeof(buffer),
range.we_version_compiled);
/* Loop back for min/max */
}
printf("\n");
}
}
printf("\n");
}
return(0);
}
#ifndef WE_ESSENTIAL
/************************** TRANSMIT POWER **************************/
/*------------------------------------------------------------------*/
/*
* Print the number of available transmit powers for the device
*/
static int
print_txpower_info(int skfd,
char * ifname,
char * args[], /* Command line args */
int count) /* Args count */
{
struct iwreq wrq;
struct iw_range range;
int dbm;
int mwatt;
int k;
/* Avoid "Unused parameter" warning */
args = args; count = count;
/* Extract range info */
if((iw_get_range_info(skfd, ifname, &range) < 0) ||
(range.we_version_compiled < 10))
fprintf(stderr, "%-8.16s no transmit-power information.\n\n",
ifname);
else
{
if((range.num_txpower <= 0) || (range.num_txpower > IW_MAX_TXPOWER))
printf("%-8.16s unknown transmit-power information.\n\n", ifname);
else
{
printf("%-8.16s %d available transmit-powers :\n",
ifname, range.num_txpower);
/* Print them all */
for(k = 0; k < range.num_txpower; k++)
{
/* Check for relative values */
if(range.txpower_capa & IW_TXPOW_RELATIVE)
{
printf("\t %d (no units)\n", range.txpower[k]);
}
else
{
if(range.txpower_capa & IW_TXPOW_MWATT)
{
dbm = iw_mwatt2dbm(range.txpower[k]);
mwatt = range.txpower[k];
}
else
{
dbm = range.txpower[k];
mwatt = iw_dbm2mwatt(range.txpower[k]);
}
printf("\t %d dBm \t(%d mW)\n", dbm, mwatt);
}
}
}
/* Get current Transmit Power */
if(iw_get_ext(skfd, ifname, SIOCGIWTXPOW, &wrq) >= 0)
{
printf(" Current Tx-Power");
/* Disabled ? */
if(wrq.u.txpower.disabled)
printf(":off\n\n");
else
{
/* Fixed ? */
if(wrq.u.txpower.fixed)
printf("=");
else
printf(":");
/* Check for relative values */
if(wrq.u.txpower.flags & IW_TXPOW_RELATIVE)
{
/* I just hate relative value, because they are
* driver specific, so not very meaningfull to apps.
* But, we have to support that, because
* this is the way hardware is... */
printf("\t %d (no units)\n", wrq.u.txpower.value);
}
else
{
if(wrq.u.txpower.flags & IW_TXPOW_MWATT)
{
dbm = iw_mwatt2dbm(wrq.u.txpower.value);
mwatt = wrq.u.txpower.value;
}
else
{
dbm = wrq.u.txpower.value;
mwatt = iw_dbm2mwatt(wrq.u.txpower.value);
}
printf("%d dBm \t(%d mW)\n\n", dbm, mwatt);
}
}
}
}
return(0);
}
/*********************** RETRY LIMIT/LIFETIME ***********************/
/*------------------------------------------------------------------*/
/*
* Print one retry value
*/
static int
get_retry_value(int skfd,
char * ifname,
struct iwreq * pwrq,
int flags,
char * buffer,
int buflen,
int we_version_compiled)
{
/* Get Another retry value */
pwrq->u.retry.flags = flags;
if(iw_get_ext(skfd, ifname, SIOCGIWRETRY, pwrq) >= 0)
{
/* Let's check the value and its type */
if(pwrq->u.retry.flags & IW_RETRY_TYPE)
{
iw_print_retry_value(buffer, buflen,
pwrq->u.retry.value, pwrq->u.retry.flags,
we_version_compiled);
printf("%s\n ", buffer);
}
}
return(pwrq->u.retry.flags);
}
/*------------------------------------------------------------------*/
/*
* Print Power Management range for each type
*/
static void
print_retry_value_range(char * name,
int mask,
int iwr_flags,
int iwr_min,
int iwr_max,
char * buffer,
int buflen,
int we_version_compiled)
{
if(iwr_flags & mask)
{
int flags = (iwr_flags & ~(IW_RETRY_MIN | IW_RETRY_MAX));
/* Display if auto or fixed */
printf("%s %s ; ",
(iwr_flags & IW_POWER_MIN) ? "Auto " : "Fixed",
name);
/* Print the range */
iw_print_retry_value(buffer, buflen,
iwr_min, flags | IW_POWER_MIN,
we_version_compiled);
printf("%s\n ", buffer);
iw_print_retry_value(buffer, buflen,
iwr_max, flags | IW_POWER_MAX,
we_version_compiled);
printf("%s\n ", buffer);
}
}
/*------------------------------------------------------------------*/
/*
* Print Retry info for each device
*/
static int
print_retry_info(int skfd,
char * ifname,
char * args[], /* Command line args */
int count) /* Args count */
{
struct iwreq wrq;
struct iw_range range;
char buffer[128];
/* Avoid "Unused parameter" warning */
args = args; count = count;
/* Extract range info */
if((iw_get_range_info(skfd, ifname, &range) < 0) ||
(range.we_version_compiled < 11))
fprintf(stderr, "%-8.16s no retry limit/lifetime information.\n\n",
ifname);
else
{
printf("%-8.16s ", ifname);
/* Display min/max limit availables */
print_retry_value_range("limit ", IW_RETRY_LIMIT, range.retry_flags,
range.min_retry, range.max_retry,
buffer, sizeof(buffer),
range.we_version_compiled);
/* Display min/max lifetime availables */
print_retry_value_range("lifetime", IW_RETRY_LIFETIME,
range.r_time_flags,
range.min_r_time, range.max_r_time,
buffer, sizeof(buffer),
range.we_version_compiled);
/* Get current retry settings */
wrq.u.retry.flags = 0;
if(iw_get_ext(skfd, ifname, SIOCGIWRETRY, &wrq) >= 0)
{
int flags = wrq.u.retry.flags;
/* Is it disabled ? */
if(wrq.u.retry.disabled)
printf("Current mode:off\n ");
else
{
unsigned int retry_type = 0;
unsigned int retry_mask = 0;
unsigned int remain_mask = range.retry_capa & IW_RETRY_TYPE;
/* Let's check the mode */
printf("Current mode:on\n ");
/* Let's check the value and its type */
if(wrq.u.retry.flags & IW_RETRY_TYPE)
{
iw_print_retry_value(buffer, sizeof(buffer),
wrq.u.retry.value, wrq.u.retry.flags,
range.we_version_compiled);
printf("%s\n ", buffer);
}
while(1)
{
/* Deal with min/max/short/long for the current value */
retry_mask = 0;
/* If we have been returned a MIN value, ask for the MAX */
if(flags & IW_RETRY_MIN)
retry_mask = IW_RETRY_MAX;
/* If we have been returned a MAX value, ask for the MIN */
if(flags & IW_RETRY_MAX)
retry_mask = IW_RETRY_MIN;
/* Same for SHORT and LONG */
if(flags & IW_RETRY_SHORT)
retry_mask = IW_RETRY_LONG;
if(flags & IW_RETRY_LONG)
retry_mask = IW_RETRY_SHORT;
/* If we have something to ask for... */
if(retry_mask)
{
retry_mask |= retry_type;
get_retry_value(skfd, ifname, &wrq, retry_mask,
buffer, sizeof(buffer),
range.we_version_compiled);
}
/* And if we have both a limit and a lifetime,
* ask the other one */
remain_mask &= ~(wrq.u.retry.flags);
retry_type = remain_mask;
/* Nothing anymore : exit the loop */
if(!retry_type)
break;
/* Ask for this other type of value */
flags = get_retry_value(skfd, ifname, &wrq, retry_type,
buffer, sizeof(buffer),
range.we_version_compiled);
/* Loop back for min/max/short/long */
}
}
}
printf("\n");
}
return(0);
}
/************************ ACCESS POINT LIST ************************/
/*
* Note : now that we have scanning support, this is depracted and
* won't survive long. Actually, next version it's out !
*/
/*------------------------------------------------------------------*/
/*
* Display the list of ap addresses and the associated stats
* Exacly the same as the spy list, only with different IOCTL and messages
*/
static int
print_ap_info(int skfd,
char * ifname,
char * args[], /* Command line args */
int count) /* Args count */
{
struct iwreq wrq;
char buffer[(sizeof(struct iw_quality) +
sizeof(struct sockaddr)) * IW_MAX_AP];
char temp[128];
struct sockaddr * hwa;
struct iw_quality * qual;
iwrange range;
int has_range = 0;
int has_qual = 0;
int n;
int i;
/* Avoid "Unused parameter" warning */
args = args; count = count;
/* Collect stats */
wrq.u.data.pointer = (caddr_t) buffer;
wrq.u.data.length = IW_MAX_AP;
wrq.u.data.flags = 0;
if(iw_get_ext(skfd, ifname, SIOCGIWAPLIST, &wrq) < 0)
{
fprintf(stderr, "%-8.16s Interface doesn't have a list of Peers/Access-Points\n\n", ifname);
return(-1);
}
/* Number of addresses */
n = wrq.u.data.length;
has_qual = wrq.u.data.flags;
/* The two lists */
hwa = (struct sockaddr *) buffer;
qual = (struct iw_quality *) (buffer + (sizeof(struct sockaddr) * n));
/* Check if we have valid mac address type */
if(iw_check_mac_addr_type(skfd, ifname) < 0)
{
fprintf(stderr, "%-8.16s Interface doesn't support MAC addresses\n\n", ifname);
return(-2);
}
/* Get range info if we can */
if(iw_get_range_info(skfd, ifname, &(range)) >= 0)
has_range = 1;
/* Display it */
if(n == 0)
printf("%-8.16s No Peers/Access-Point in range\n", ifname);
else
printf("%-8.16s Peers/Access-Points in range:\n", ifname);
for(i = 0; i < n; i++)
{
if(has_qual)
{
/* Print stats for this address */
printf(" %s : ", iw_saether_ntop(&hwa[i], temp));
iw_print_stats(temp, sizeof(buffer), &qual[i], &range, has_range);
printf("%s\n", temp);
}
else
/* Only print the address */
printf(" %s\n", iw_saether_ntop(&hwa[i], temp));
}
printf("\n");
return(0);
}
/******************** WIRELESS EVENT CAPABILITY ********************/
static const char * event_capa_req[] =
{
[SIOCSIWNWID - SIOCIWFIRST] = "Set NWID (kernel generated)",
[SIOCSIWFREQ - SIOCIWFIRST] = "Set Frequency/Channel (kernel generated)",
[SIOCGIWFREQ - SIOCIWFIRST] = "New Frequency/Channel",
[SIOCSIWMODE - SIOCIWFIRST] = "Set Mode (kernel generated)",
[SIOCGIWTHRSPY - SIOCIWFIRST] = "Spy threshold crossed",
[SIOCGIWAP - SIOCIWFIRST] = "New Access Point/Cell address - roaming",
[SIOCGIWSCAN - SIOCIWFIRST] = "Scan request completed",
[SIOCSIWESSID - SIOCIWFIRST] = "Set ESSID (kernel generated)",
[SIOCGIWESSID - SIOCIWFIRST] = "New ESSID",
[SIOCGIWRATE - SIOCIWFIRST] = "New bit-rate",
[SIOCSIWENCODE - SIOCIWFIRST] = "Set Encoding (kernel generated)",
[SIOCGIWPOWER - SIOCIWFIRST] = NULL,
};
static const char * event_capa_evt[] =
{
[IWEVTXDROP - IWEVFIRST] = "Tx packet dropped - retry exceeded",
[IWEVCUSTOM - IWEVFIRST] = "Custom driver event",
[IWEVREGISTERED - IWEVFIRST] = "Registered node",
[IWEVEXPIRED - IWEVFIRST] = "Expired node",
};
/*------------------------------------------------------------------*/
/*
* Print the event capability for the device
*/
static int
print_event_capa_info(int skfd,
char * ifname,
char * args[], /* Command line args */
int count) /* Args count */
{
struct iw_range range;
int cmd;
/* Avoid "Unused parameter" warning */
args = args; count = count;
/* Extract range info */
if((iw_get_range_info(skfd, ifname, &range) < 0) ||
(range.we_version_compiled < 10))
fprintf(stderr, "%-8.16s no wireless event capability information.\n\n",
ifname);
else
{
#ifdef DEBUG
/* Debugging ;-) */
for(cmd = 0x8B00; cmd < 0x8C0F; cmd++)
{
int idx = IW_EVENT_CAPA_INDEX(cmd);
int mask = IW_EVENT_CAPA_MASK(cmd);
printf("0x%X - %d - %X\n", cmd, idx, mask);
}
#endif
printf("%-8.16s Wireless Events supported :\n", ifname);
for(cmd = SIOCIWFIRST; cmd <= SIOCGIWPOWER; cmd++)
{
int idx = IW_EVENT_CAPA_INDEX(cmd);
int mask = IW_EVENT_CAPA_MASK(cmd);
if(range.event_capa[idx] & mask)
printf(" 0x%04X : %s\n",
cmd, event_capa_req[cmd - SIOCIWFIRST]);
}
for(cmd = IWEVFIRST; cmd <= IWEVEXPIRED; cmd++)
{
int idx = IW_EVENT_CAPA_INDEX(cmd);
int mask = IW_EVENT_CAPA_MASK(cmd);
if(range.event_capa[idx] & mask)
printf(" 0x%04X : %s\n",
cmd, event_capa_evt[cmd - IWEVFIRST]);
}
printf("\n");
}
return(0);
}
/*************************** WPA SUPPORT ***************************/
/*------------------------------------------------------------------*/
/*
* Print the authentication parameters for the device
*/
static int
print_auth_info(int skfd,
char * ifname,
char * args[], /* Command line args */
int count) /* Args count */
{
struct iwreq wrq;
struct iw_range range;
unsigned int k;
/* Avoid "Unused parameter" warning */
args = args; count = count;
/* Extract range info */
if((iw_get_range_info(skfd, ifname, &range) < 0) ||
(range.we_version_compiled < 18))
fprintf(stderr, "%-8.16s no authentication information.\n\n",
ifname);
else
{
/* Print WPA/802.1x/802.11i security parameters */
if(!range.enc_capa)
{
printf("%-8.16s unknown authentication information.\n\n", ifname);
}
else
{
/* Display advanced encryption capabilities */
printf("%-8.16s Authentication capabilities :", ifname);
iw_print_mask_name(range.enc_capa,
iw_auth_capa_name, IW_AUTH_CAPA_NUM,
"\n\t\t");
printf("\n");
/* Extract all auth settings */
for(k = 0; k < IW_AUTH_SETTINGS_NUM; k++)
{
wrq.u.param.flags = iw_auth_settings[k].value;
if(iw_get_ext(skfd, ifname, SIOCGIWAUTH, &wrq) >= 0)
{
printf(" Current %s :", iw_auth_settings[k].label);
if(iw_auth_settings[k].names != NULL)
iw_print_mask_name(wrq.u.param.value,
iw_auth_settings[k].names,
iw_auth_settings[k].num_names,
"\n\t\t");
else
printf((wrq.u.param.value) ? " yes" : " no");
printf("\n");
}
}
}
printf("\n\n");
}
return(0);
}
/*------------------------------------------------------------------*/
/*
* Print all the available wpa keys for the device
*/
static int
print_wpakeys_info(int skfd,
char * ifname,
char * args[], /* Command line args */
int count) /* Args count */
{
struct iwreq wrq;
struct iw_range range;
unsigned char extbuf[IW_EXTKEY_SIZE];
struct iw_encode_ext *extinfo;
unsigned int k;
char buffer[128];
/* Avoid "Unused parameter" warning */
args = args; count = count;
/* This always point to the same place */
extinfo = (struct iw_encode_ext *) extbuf;
/* Extract range info */
if(iw_get_range_info(skfd, ifname, &range) < 0)
fprintf(stderr, "%-8.16s no wpa key information.\n\n",
ifname);
else
{
printf("%-8.16s ", ifname);
/* Print key sizes */
if((range.num_encoding_sizes > 0) &&
(range.num_encoding_sizes < IW_MAX_ENCODING_SIZES))
{
printf("%d key sizes : %d", range.num_encoding_sizes,
range.encoding_size[0] * 8);
/* Print them all */
for(k = 1; k < range.num_encoding_sizes; k++)
printf(", %d", range.encoding_size[k] * 8);
printf("bits\n ");
}
/* Print the keys */
printf("%d keys available :\n", range.max_encoding_tokens);
for(k = 1; k <= range.max_encoding_tokens; k++)
{
/* Cleanup. Driver may not fill everything */
memset(extbuf, '\0', IW_EXTKEY_SIZE);
/* Get whole struct containing one WPA key */
wrq.u.data.pointer = (caddr_t) extbuf;
wrq.u.data.length = IW_EXTKEY_SIZE;
wrq.u.data.flags = k;
if(iw_get_ext(skfd, ifname, SIOCGIWENCODEEXT, &wrq) < 0)
{
fprintf(stderr, "Error reading wpa keys (SIOCGIWENCODEEXT): %s\n", strerror(errno));
break;
}
/* Sanity check */
if(wrq.u.data.length <
(sizeof(struct iw_encode_ext) + extinfo->key_len))
break;
/* Check if key is disabled */
if((wrq.u.data.flags & IW_ENCODE_DISABLED) ||
(extinfo->key_len == 0))
printf("\t\t[%d]: off\n", k);
else
{
/* Display the key */
iw_print_key(buffer, sizeof(buffer),
extinfo->key, extinfo->key_len, wrq.u.data.flags);
printf("\t\t[%d]: %s", k, buffer);
/* Key size */
printf(" (%d bits)", extinfo->key_len * 8);
printf("\n");
/* Other info... */
printf("\t\t Address: %s\n",
iw_saether_ntop(&extinfo->addr, buffer));
printf("\t\t Algorithm:");
iw_print_value_name(extinfo->alg,
iw_encode_alg_name, IW_ENCODE_ALG_NUM);
printf("\n\t\t Flags: 0x%08x\n", extinfo->ext_flags);
if (extinfo->ext_flags & IW_ENCODE_EXT_TX_SEQ_VALID)
printf("\t\t tx-seq-valid\n");
if (extinfo->ext_flags & IW_ENCODE_EXT_RX_SEQ_VALID)
printf("\t\t rx-seq-valid\n");
if (extinfo->ext_flags & IW_ENCODE_EXT_GROUP_KEY)
printf("\t\t group-key\n");
}
}
/* Print current key index and mode */
wrq.u.data.pointer = (caddr_t) extbuf;
wrq.u.data.length = IW_EXTKEY_SIZE;
wrq.u.data.flags = 0; /* Set index to zero to get current */
if(iw_get_ext(skfd, ifname, SIOCGIWENCODEEXT, &wrq) >= 0)
{
/* Note : if above fails, we have already printed an error
* message int the loop above */
printf(" Current Transmit Key: [%d]\n",
wrq.u.data.flags & IW_ENCODE_INDEX);
if(wrq.u.data.flags & IW_ENCODE_RESTRICTED)
printf(" Security mode:restricted\n");
if(wrq.u.data.flags & IW_ENCODE_OPEN)
printf(" Security mode:open\n");
}
printf("\n\n");
}
return(0);
}
/*------------------------------------------------------------------*/
/*
* Print the Generic IE for the device
* Note : indentation is broken. We need to fix that.
*/
static int
print_gen_ie_info(int skfd,
char * ifname,
char * args[], /* Command line args */
int count) /* Args count */
{
struct iwreq wrq;
unsigned char buf[IW_GENERIC_IE_MAX];
/* Avoid "Unused parameter" warning */
args = args; count = count;
wrq.u.data.pointer = (caddr_t)buf;
wrq.u.data.length = IW_GENERIC_IE_MAX;
wrq.u.data.flags = 0;
if(iw_get_ext(skfd, ifname, SIOCGIWGENIE, &wrq) < 0)
fprintf(stderr, "%-8.16s no generic IE (%s).\n\n",
ifname, strerror(errno));
else
{
fprintf(stderr, "%-8.16s\n", ifname);
if(wrq.u.data.length == 0)
printf(" empty generic IE\n");
else
iw_print_gen_ie(buf, wrq.u.data.length);
printf("\n");
}
return(0);
}
/**************************** MODULATION ****************************/
/*------------------------------------------------------------------*/
/*
* Print Modulation info for each device
*/
static int
print_modul_info(int skfd,
char * ifname,
char * args[], /* Command line args */
int count) /* Args count */
{
struct iwreq wrq;
struct iw_range range;
/* Avoid "Unused parameter" warning */
args = args; count = count;
/* Extract range info */
if((iw_get_range_info(skfd, ifname, &range) < 0) ||
(range.we_version_compiled < 11))
fprintf(stderr, "%-8.16s no modulation information.\n\n",
ifname);
else
{
if(range.modul_capa == 0x0)
printf("%-8.16s unknown modulation information.\n\n", ifname);
else
{
int i;
printf("%-8.16s Modulations available :\n", ifname);
/* Display each modulation available */
for(i = 0; i < IW_SIZE_MODUL_LIST; i++)
{
if((range.modul_capa & iw_modul_list[i].mask)
== iw_modul_list[i].mask)
printf(" %-8s: %s\n",
iw_modul_list[i].cmd, iw_modul_list[i].verbose);
}
/* Get current modulations settings */
wrq.u.param.flags = 0;
if(iw_get_ext(skfd, ifname, SIOCGIWMODUL, &wrq) >= 0)
{
unsigned int modul = wrq.u.param.value;
int n = 0;
printf(" Current modulations %c",
wrq.u.param.fixed ? '=' : ':');
/* Display each modulation enabled */
for(i = 0; i < IW_SIZE_MODUL_LIST; i++)
{
if((modul & iw_modul_list[i].mask) == iw_modul_list[i].mask)
{
if((n++ % 8) == 0)
printf("\n ");
else
printf(" ; ");
printf("%s", iw_modul_list[i].cmd);
}
}
printf("\n");
}
printf("\n");
}
}
return(0);
}
#endif /* WE_ESSENTIAL */
/************************* COMMON UTILITIES *************************/
/*
* This section was initially written by <NAME> <<EMAIL>>
* but heavily modified by me ;-)
*/
/*------------------------------------------------------------------*/
/*
* Map command line arguments to the proper procedure...
*/
typedef struct iwlist_entry {
const char * cmd; /* Command line shorthand */
iw_enum_handler fn; /* Subroutine */
int max_count;
const char * argsname; /* Args as human readable string */
} iwlist_cmd;
static const struct iwlist_entry iwlist_cmds[] = {
{ "scanning", print_scanning_info, -1, "[essid NNN] [last]" },
{ "frequency", print_freq_info, 0, NULL },
{ "channel", print_freq_info, 0, NULL },
{ "bitrate", print_bitrate_info, 0, NULL },
{ "rate", print_bitrate_info, 0, NULL },
{ "encryption", print_keys_info, 0, NULL },
{ "keys", print_keys_info, 0, NULL },
{ "power", print_pm_info, 0, NULL },
#ifndef WE_ESSENTIAL
{ "txpower", print_txpower_info, 0, NULL },
{ "retry", print_retry_info, 0, NULL },
{ "ap", print_ap_info, 0, NULL },
{ "accesspoints", print_ap_info, 0, NULL },
{ "peers", print_ap_info, 0, NULL },
{ "event", print_event_capa_info, 0, NULL },
{ "auth", print_auth_info, 0, NULL },
{ "wpakeys", print_wpakeys_info, 0, NULL },
{ "genie", print_gen_ie_info, 0, NULL },
{ "modulation", print_modul_info, 0, NULL },
#endif /* WE_ESSENTIAL */
{ NULL, NULL, 0, 0 },
};
/*------------------------------------------------------------------*/
/*
* Find the most appropriate command matching the command line
*/
static inline const iwlist_cmd *
find_command(const char * cmd)
{
const iwlist_cmd * found = NULL;
int ambig = 0;
unsigned int len = strlen(cmd);
int i;
/* Go through all commands */
for(i = 0; iwlist_cmds[i].cmd != NULL; ++i)
{
/* No match -> next one */
if(strncasecmp(iwlist_cmds[i].cmd, cmd, len) != 0)
continue;
/* Exact match -> perfect */
if(len == strlen(iwlist_cmds[i].cmd))
return &iwlist_cmds[i];
/* Partial match */
if(found == NULL)
/* First time */
found = &iwlist_cmds[i];
else
/* Another time */
if (iwlist_cmds[i].fn != found->fn)
ambig = 1;
}
if(found == NULL)
{
fprintf(stderr, "iwlist: unknown command `%s' (check 'iwlist --help').\n", cmd);
return NULL;
}
if(ambig)
{
fprintf(stderr, "iwlist: command `%s' is ambiguous (check 'iwlist --help').\n", cmd);
return NULL;
}
return found;
}
/*------------------------------------------------------------------*/
/*
* Display help
*/
static void iw_usage(int status)
{
FILE * f = status ? stderr : stdout;
int i;
for(i = 0; iwlist_cmds[i].cmd != NULL; ++i)
{
fprintf(f, "%s [interface] %s %s\n",
(i ? " " : "Usage: iwlist"),
iwlist_cmds[i].cmd,
iwlist_cmds[i].argsname ? iwlist_cmds[i].argsname : "");
}
return ;
}
/******************************* MAIN ********************************/
/*------------------------------------------------------------------*/
/*
* The main !
*/
int
iwlist(int argc,
char ** argv,void *ap_info,int *ap_cnt)
{
int skfd; /* generic raw socket desc. */
char *dev; /* device name */
char *cmd; /* command */
char **args; /* Command arguments */
int count; /* Number of arguments */
const iwlist_cmd *iwcmd;
if(argc < 2)
iw_usage(1);
/* Those don't apply to all interfaces */
if((argc == 2) && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")))
iw_usage(0);
if((argc == 2) && (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")))
return(iw_print_version_info("iwlist"));
if(argc == 2)
{
cmd = argv[1];
dev = NULL;
args = NULL;
count = 0;
}
else
{
cmd = argv[2];
dev = argv[1];
args = argv + 3;
count = argc - 3;
}
/* find a command */
iwcmd = find_command(cmd);
if(iwcmd == NULL)
return 1;
/* Check arg numbers */
if((iwcmd->max_count >= 0) && (count > iwcmd->max_count))
{
fprintf(stderr, "iwlist: command `%s' needs fewer arguments (max %d)\n",
iwcmd->cmd, iwcmd->max_count);
return 1;
}
/* Create a channel to the NET kernel. */
if((skfd = iw_sockets_open()) < 0)
{
perror("socket");
return -1;
}
g_ap_info = (TcWifiScan *)ap_info ;
g_ap_cnt = ap_cnt;
/* do the actual work */
if (dev)
(*iwcmd->fn)(skfd, dev, args, count);
else
iw_enum_devices(skfd, iwcmd->fn, args, count);
/* Close the socket. */
iw_sockets_close(skfd);
return 0;
}
<file_sep>/src/gui/my_controls/my_button.h
/*
* =============================================================================
*
* Filename: my_button.h
*
* Description: 自定义皮肤按键
*
* Version: 1.0
* Created: 2019-04-23 19:46:14
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_BUTTON_H
#define _MY_BUTTON_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include "my_controls.h"
#include "commongdi.h"
#define CTRL_MYBUTTON ("mybutton")
enum { // 按钮类型
MYBUTTON_TYPE_ONE_STATE = (1 << 0),
MYBUTTON_TYPE_TWO_STATE = (1 << 1),
MYBUTTON_TYPE_CHECKBOX = (1 << 2),
MYBUTTON_TYPE_TEXT_CENTER = (1 << 10), // 文字居中,否则在最底部
MYBUTTON_TYPE_PRESS_COLOR = (1 << 11), // 背景是否为纯色,否则为图片
MYBUTTON_TYPE_PRESS_TRANSLATE = (1 << 12), // 无背景色
MYBUTTON_TYPE_TEXT_NULL = (1 << 13), // 无文字
};
enum {
BUT_NORMAL, // 正常
BUT_CLICK, // 按下
BUT_DISABLED, // 不启用
};
enum {
MYBUTTON_STATE_UNCHECK, // 非选择状态
MYBUTTON_STATE_CHECK, // 选择状态
};
typedef struct {
const char *text; // 文字
PLOGFONT font; // 字体
BITMAP *image_normal; // 正常状态图片
BITMAP *image_press; // 按下状态图片
BITMAP *image_select; // 选中图片
BITMAP *image_unselect; // 非选中图片
unsigned int color_nor,color_press;// 文字颜色,正常颜色与按下颜色,默认为白色
int flag; // 按扭类型
int state; //BUTTON状态
int check; // 选中状态
}MyButtonCtrlInfo;
typedef struct _MyCtrlButton{
HWND idc; // 控件ID
int flag; // 按钮类型
char *img_name; // 常态图片名字,不带扩展名,完整路径由循环赋值
int16_t x,y;
NOTIFPROC notif_proc; // 回调函数
PLOGFONT font; // 字体
BITMAP image_normal; // 正常状态图片
BITMAP image_press; // 按下状态图片
int16_t w,h;
unsigned color_nor,color_press;// 文字颜色,正常颜色与按下颜色,默认为白色
}MyCtrlButton;
HWND createMyButton(HWND hWnd,MyCtrlButton *button);
MyControls *my_button;
void initMyButton(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/rdface/CMakeLists.txt
# 查找当前目录下的所有源文件 并将名称保存到 SRCS_RDFACE 变量
aux_source_directory(. SRCS_RDFACE)
# 生成链接库
add_library (rdface ${SRCS_RDFACE})
target_link_libraries(rdface
rsface ion rkrga pthread
)
<file_sep>/src/drivers/ipc_server.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdlib.h>
#include "thread_helper.h"
#include "ipc_server.h"
typedef struct _IpcServerPriv {
char ipc_path[64];
int listen_fd;
int send_fd;
IpcCallback callbackFunc;
}IpcServerPriv;
void waitIpcOpen(const char *path)
{
int fd = -1;
while (1) {
fd = access(path,0);
if (fd != 0) {
// printf("open ipc :%s fail,error:%s\n",path ,strerror(errno));
sleep(1);
continue;
}
close(fd);
// 等待主程序IPC初始化完成
sleep(3);
return;
}
}
static int sendData(struct _IpcServer *This,const char *path,void *data,int size)
{
static struct sockaddr_un srv_addr;
This->priv->send_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if(This->priv->send_fd < 0) {
perror("cannot create communication socket");
return -1;
}
srv_addr.sun_family = AF_UNIX;
strcpy(srv_addr.sun_path,(char *)path);
//connect server
int ret = connect(This->priv->send_fd, (struct sockaddr*)&srv_addr, sizeof(srv_addr));
if(ret == -1) {
// perror("cannot connect to the server");
close(This->priv->send_fd);
return -1;
}
write(This->priv->send_fd, data, size);
close(This->priv->send_fd);
return 0;
}
static void* threadIpcRecieved(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
struct sockaddr_un clt_addr;
IpcServer *This = (IpcServer *)arg;
int len;
char data_buf[1024];
while (1) {
len = sizeof(clt_addr);
int com_fd = accept(This->priv->listen_fd,(struct sockaddr*)&clt_addr,&len);
if(com_fd < 0) {
perror("cannot accept client connect request");
continue;
}
memset(data_buf, 0, 1024);
int size = read(com_fd, data_buf, sizeof(data_buf));
if (This->priv->callbackFunc)
This->priv->callbackFunc(data_buf,size);
close(com_fd);
}
return NULL;
}
static int ipcInit(IpcServer *This)
{
struct sockaddr_un srv_addr;
int ret = -1;
This->priv->listen_fd = socket(PF_UNIX, SOCK_STREAM, 0);
if(This->priv->listen_fd < 0) {
perror("cannot create communication socket");
return -1;
}
//set server addr_param
srv_addr.sun_family = AF_UNIX;
strcpy(srv_addr.sun_path,This->priv->ipc_path);
unlink(This->priv->ipc_path);
//bind sockfd & addr
ret = bind(This->priv->listen_fd, (struct sockaddr*)&srv_addr, sizeof(srv_addr));
if(ret == -1) {
perror("cannot bind server socket");
close(This->priv->listen_fd);
unlink(This->priv->ipc_path);
return -1;
}
//listen sockfd
ret = listen(This->priv->listen_fd,1);
if(ret == -1) {
perror("cannot listen the client connect request");
close(This->priv->listen_fd);
unlink(This->priv->ipc_path);
return -1;
}
createThread(threadIpcRecieved,This);
return 0;
}
IpcServer* ipcCreate(const char *path,IpcCallback func)
{
IpcServer* This = (IpcServer*) calloc(1,sizeof(IpcServer));
if (This == NULL) {
perror("err to create ipc this\n");
return NULL;
}
This->priv = (IpcServerPriv*) calloc(1,sizeof(IpcServerPriv));
if (This->priv == NULL) {
perror("err to create ipc priv\n");
free(This);
return NULL;
}
strcpy(This->priv->ipc_path,path);
This->priv->callbackFunc = func;
This->sendData = sendData;
int ret = ipcInit(This);
if (ret == -1) {
printf("ipc[%s] init fail\n",path);
free(This->priv);
free(This);
return NULL;
}
return This;
}
<file_sep>/src/app/CMakeLists.txt
# 查找当前目录下的所有源文件 并将名称保存到 SRCS_APP 变量
aux_source_directory(. SRCS_APP)
STRING( REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER_APP ${CMAKE_CURRENT_SOURCE_DIR})
if (MODE_UCPAAS)
set(SUB_DIRS_APP ${SUB_DIRS_APP} ucpaas )
endif()
if (MODE_VIDEO)
set(SUB_DIRS_APP ${SUB_DIRS_APP} video )
endif()
if (MODE_FACE)
set(SUB_DIRS_APP ${SUB_DIRS_APP} rdface )
endif()
if (MODE_UDPTALK)
set(SUB_DIRS_APP ${SUB_DIRS_APP} udp_talk )
endif()
foreach(sub ${SUB_DIRS_APP})
add_subdirectory(${sub})
endforeach()
# 生成链接库
add_library (${CURRENT_FOLDER_APP} ${SRCS_APP})
target_link_libraries (${CURRENT_FOLDER_APP} ${SUB_DIRS_APP})
<file_sep>/src/drivers/thread_helper.c
#include <stdio.h>
#include "thread_helper.h"
int createThread(void *(*start_routine)(void *), void *arg)
{
int result;
pthread_t task;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
result = pthread_create(&task, &attr, start_routine, arg);
if(result)
printf("create thread failt,Error code:%d\n",result);
pthread_attr_destroy(&attr);
return task;
}
<file_sep>/src/drivers/share_memory.h
/*
* =============================================================================
*
* Filename: share_memory.h
*
* Description: 共享内存管理
*
* Version: 1.0
* Created: 2019-07-27 16:20:04
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _SHARE_MEMORY_H
#define _SHARE_MEMORY_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <pthread.h>
#include <semaphore.h>
typedef struct _ShareMemoryData {
int size;
char data[1];
}ShareMemoryData;
struct _ShareMemoryPrivate;
typedef struct _ShareMemory
{
struct _ShareMemoryPrivate *Private;
unsigned int (*WriteCnt)(struct _ShareMemory *This); //返回写入的缓冲区数量
char* (*SaveStart)(struct _ShareMemory *This); //获得写句柄
void (*SaveEnd)(struct _ShareMemory *This,int Size); //释放写句柄,Size为写入字节数
char* (*GetStart)(struct _ShareMemory *This,int *Size); //获得读句柄,Size为缓冲区字节数
void (*GetEnd)(struct _ShareMemory *This); //释放读句柄
// void (* InitSem)(struct _ShareMemory *This); //初始化信号
void (* CloseMemory)(struct _ShareMemory *This); //结束
void (* Destroy)(struct _ShareMemory *This); //销毁该ShareMemory
int (* My_sem_post_get)(struct _ShareMemory *This);
int (* My_sem_post_save)(struct _ShareMemory *This);
int (* My_sem_wait_get)(struct _ShareMemory *This);
int (* My_sem_wait_save)(struct _ShareMemory *This);
}ShareMemory,*PShareMemory;
ShareMemory* CreateShareMemory(unsigned int Size,unsigned int BufCnt,int type);
ShareMemory * shareMemoryCreateMaster(unsigned int Size,unsigned int BufCnt);
ShareMemory * shareMemoryCreateSlave(unsigned int Size,unsigned int BufCnt);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/hal/hal_gpio.c
/*
* =============================================================================
*
* Filename: hal_gpio.c
*
* Description: 硬件层 GPIO控制
*
* Version: 1.0
* Created: 2018-12-12 16:26:55
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include "gpio-rv1108.h"
#include "hal_gpio.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
typedef struct {
char ioname[16];
int iovalue;
} TioLevelCtrl;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static int fd = -1;
void halGpioSetMode(int port_id,char* port_name,int dir)
{
if (fd < 0) {
#ifndef X86
fd = open("/dev/rv1108gpio",O_RDWR);
#endif
} else {
return;
}
return;
}
void halGpioOut(int port_id,char *port_name,int value)
{
if (fd < 0) {
return;
}
#ifndef X86
TioLevelCtrl sbuf;
strcpy(sbuf.ioname,port_name);
sbuf.iovalue = value;
int ret = ioctl(fd, RV1108_IOCGPIO_CTRL, &sbuf);
if(ret < 0)
printf("[%s]name:%s,v:%d\n",__func__,port_name,value);
return;
#endif
}
int halGpioIn(int port_id,char *port_name)
{
#ifdef X86
return 0;
#endif
}
<file_sep>/src/app/externfunc.h
#ifndef EXTERNFUNC_H
#define EXTERNFUNC_H
#include <stdint.h>
typedef struct _st_dir {
char path[128]; // 文件名称 包括路径
void * data; // 文件
}ST_DIR;
#define SaveLog(fmt,arg...) \
do { \
char RecDate[50]; \
FILE *log_fd; \
getDate(RecDate,sizeof(RecDate)); \
log_fd = fopen("log.txt","a+"); \
fprintf(log_fd,"%s:[%s]",RecDate,__FUNCTION__); \
fprintf(log_fd,fmt,##arg); \
fflush(log_fd); \
fclose(log_fd); \
} while(0) \
//---------------------------------------------------------------------------
//外部函数
//---------------------------------------------------------------------------
int fileexists(const char *FileName);
char *strupper(char *pdst,const char *pstr,int Size);
void DelayMs(int ms);
char * excuteCmd(char *Cmd,...);
void ErrorLog(int ecode,const char *fmt,...);
char * getDate(char *cBuf,int Size);
const char * GetSendIP(const char *pSrcIP,const char *pDestIP,const char *pMask);
int jugdeRecIP(const char *pSrcIP,const char *pDestIP,const char *pMask);
unsigned int my_inet_addr(const char *IP);
void SetNetwork(int flag,const char *cIp,const char *cMask,const char *cGateWay,const char *cMac);
void SetNetMac(unsigned char *pImei,char *MAC);
uint64_t getMs(void);
void backData(char *file);
unsigned long long GetFlashFreeSpace(void);
unsigned long long GetFlashFreeSpaceKB(void);
unsigned long long GetFlashFreeSpaceMB(void);
void print_data(char *data,int len);
int GetFilesNum(char *pPathDir,void (*func)(void *));
int recoverData(const char *file);
struct tm * getTime(void);
int getWifiList(void *ap_info,void (*callback)(void *ap_info,int ap_cnt));
int getWifiConfig(int *qual);
void wifiConnectStart(void);
void wifiConnect(void);
void wifiDisConnect(void);
int screensaverSet(int state);
void getFileName(char *file_name,char *date);
void getCpuId(char *hardcode);
uint64_t MyGetTickCount(void);
int GetFileSize(char *file);
int getLocalIP(char *IP,char *gateway);
int getGateWayMac(char *gateway,char *mac);
void powerOff(void);
void reboot(void);
int checkSD(void);
int getSdMem(char *total,char *residue,char *used);
int adjustdate(int year,int mon,int mday,int hour,int min,int sec);
void getVersionInfo(char *ver,int *major,int *minor,int *release);
void setSysVolume(int volume);
int screenSetBrightness(int brightness);
void getKernelVersion(char *version,int leng);
#endif
<file_sep>/src/drivers/uart.h
/*
* =============================================================================
*
* Filename: uart.h
*
* Description: uart driver
*
* Version: 1.0
* Created: 2016-08-06 16:49:21
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _UART_H
#define _UART_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <stdint.h>
#define MAX_SEND_BUFF 128
#if 1
#define DEBUG_UART(dir,pbuf,size) \
do { \
int i;\
unsigned char *pData = (unsigned char *)pbuf;\
DPRINT("[uart-->%s,%d]",dir,size);\
for(i=0;i<size;i++) {\
DPRINT("%02X ",pData[i]);\
}\
DPRINT("\n");\
} while (0)
#else
#define DEBUG_UART(dir,pbuf,size)
#endif
struct _UartServerPriv;
typedef struct _UartServer{
struct _UartServerPriv *priv;
int (*open)(struct _UartServer *This,int port,int baudrate);
int (*send)(struct _UartServer *This,void *Buf,int datalen);
//接收数据,直至5MS内没有数据返回
int (*recvBuffer)(struct _UartServer *This,void *Buf,uint32_t BufSize);
int (*waitFor)(struct _UartServer *This,unsigned int Ms);
void (*clear)(struct _UartServer *This);
void (*close)(struct _UartServer *This);
void (*destroy)(struct _UartServer *This);
}UartServer;
extern UartServer *uartServerCreate(void (*func)(void));
extern void uartInit(void(*func)(void));
extern UartServer *uart;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/gui/my_controls/my_title.c
/*
* =====================================================================================
*
* Filename: MyTitle.c
*
* Description: 自定义按钮
*
* Version: 1.0
* Created: 2015-12-09 16:22:37
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
/* ----------------------------------------------------------------*
* include head files
*-----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include "my_title.h"
#include "debug.h"
#include "cliprect.h"
#include "internals.h"
#include "ctrlclass.h"
/* ----------------------------------------------------------------*
* extern variables declare
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*
* internal functions declare
*-----------------------------------------------------------------*/
static int myTitleControlProc (HWND hwnd, int message, WPARAM wParam, LPARAM lParam);
/* ----------------------------------------------------------------*
* macro define
*-----------------------------------------------------------------*/
#define CTRL_NAME CTRL_MYTITLE
/* ----------------------------------------------------------------*
* variables define
*-----------------------------------------------------------------*/
MyControls *my_title;
static BITMAP image_swich_off;// 关闭状态图片
static BITMAP image_swich_on; // 打开状态图片
static BITMAP image_add; // 添加按钮图片
static BITMAP image_exit; // 退出按钮图片
static BmpLocation base_bmps[] = {
{&image_swich_off,"setting/Switch Off_小.png"},
{&image_swich_on, "setting/Switch On_小.png"},
{&image_add, "setting/ico_添加.png"},
{&image_exit, "setting/arrow-back.png"},
{NULL},
};
/* ---------------------------------------------------------------------------*/
/**
* @brief myTitleRegist 注册控件
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static BOOL myTitleRegist (void)
{
WNDCLASS WndClass;
WndClass.spClassName = CTRL_NAME;
WndClass.dwStyle = WS_NONE;
WndClass.dwExStyle = WS_EX_NONE;
WndClass.hCursor = GetSystemCursor (IDC_ARROW);
WndClass.iBkColor = 0;
WndClass.WinProc = myTitleControlProc;
return RegisterWindowClass(&WndClass);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myTitleCleanUp 卸载控件
*/
/* ---------------------------------------------------------------------------*/
static void myTitleCleanUp (void)
{
UnregisterWindowClass(CTRL_NAME);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief clickInButton 判断触摸坐标是否在按钮内
*
* @param pInfo
* @param x
* @param y
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int clickInButton(MyTitleCtrlInfo* pInfo,int x,int y)
{
// 在原有图标返回上扩大触摸范围,提高手感
#define EXTEND_RC(hrc,offset) \
do { \
hrc.left -= offset; \
hrc.right += offset; \
hrc.top -= offset; \
hrc.bottom += offset; \
} while (0)
RECT rc ;
int ret = MYTITLE_BUTTON_NULL;
if (pInfo->flag_left == MYTITLE_LEFT_EXIT) {
memcpy(&rc,&pInfo->bt_exit.rc,sizeof(RECT));
EXTEND_RC(rc,10);
if (PtInRect (&rc, x, y) && PtInRect (&rc, pInfo->click_x, pInfo->click_y))
return MYTITLE_BUTTON_EXIT;
}
if (pInfo->flag_right == MYTITLE_RIGHT_ADD) {
memcpy(&rc,&pInfo->bt_add.rc,sizeof(RECT));
EXTEND_RC(rc,10);
if (PtInRect (&rc, x, y) && PtInRect (&rc, pInfo->click_x, pInfo->click_y))
ret = MYTITLE_BUTTON_ADD;
} else if (pInfo->flag_right == MYTITLE_RIGHT_SWICH) {
memcpy(&rc,&pInfo->bt_swich.rc,sizeof(RECT));
EXTEND_RC(rc,10);
if (PtInRect (&rc, x, y) && PtInRect (&rc, pInfo->click_x, pInfo->click_y)) {
ret = MYTITLE_BUTTON_SWICH;
if (pInfo->bt_swich.state == MYTITLE_SWICH_ON)
pInfo->bt_swich.state = MYTITLE_SWICH_OFF;
else
pInfo->bt_swich.state = MYTITLE_SWICH_ON;
}
} else if (pInfo->flag_right == MYTITLE_RIGHT_TEXT) {
// 右边文字使用SWICH_BUTTON位置
memcpy(&rc,&pInfo->bt_swich.rc,sizeof(RECT));
EXTEND_RC(rc,10);
if (PtInRect (&rc, x, y) && PtInRect (&rc, pInfo->click_x, pInfo->click_y))
ret = MYTITLE_BUTTON_TEXT;
}
return ret;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief paint 主要绘图函数
*
* @param hWnd
* @param hdc
*/
/* ---------------------------------------------------------------------------*/
static void paint(HWND hWnd,HDC hdc)
{
#define FILL_BMP_STRUCT(rc,img) rc.left, rc.top,img->bmWidth,img->bmHeight,img
RECT rc_bmp,rc_text;
PCONTROL pCtrl;
pCtrl = Control (hWnd);
GetClientRect (hWnd, &rc_bmp);
rc_text = rc_bmp;
if (!pCtrl->dwAddData2)
return;
MyTitleCtrlInfo* pInfo = (MyTitleCtrlInfo*)(pCtrl->dwAddData2);
// 绘制背景色
myFillBox(hdc,&rc_bmp,pInfo->bkg_color);
// 写标题
SetTextColor(hdc,pInfo->font_color);
SetBkMode(hdc,BM_TRANSPARENT);
SelectFont (hdc, pInfo->font);
DrawText (hdc,pInfo->text, -1, &rc_text,
DT_CENTER | DT_VCENTER | DT_WORDBREAK | DT_SINGLELINE);
if (pInfo->flag_left == MYTITLE_LEFT_EXIT) {
FillBoxWithBitmap(hdc,FILL_BMP_STRUCT(pInfo->bt_exit.rc,pInfo->bt_exit.image_nor));
}
if (pInfo->flag_right == MYTITLE_RIGHT_TEXT) {
rc_text.left = 930;
DrawText (hdc,pInfo->text_right, -1, &rc_text,
DT_CENTER | DT_VCENTER | DT_WORDBREAK | DT_SINGLELINE);
} else if (pInfo->flag_right == MYTITLE_RIGHT_ADD) {
FillBoxWithBitmap(hdc,FILL_BMP_STRUCT(pInfo->bt_add.rc,pInfo->bt_add.image_nor));
} else if (pInfo->flag_right == MYTITLE_RIGHT_SWICH) {
if (pInfo->bt_swich.state == MYTITLE_SWICH_ON) {
FillBoxWithBitmap(hdc,FILL_BMP_STRUCT(pInfo->bt_swich.rc,pInfo->bt_swich.image_pre));
} else {
FillBoxWithBitmap(hdc,FILL_BMP_STRUCT(pInfo->bt_swich.rc,pInfo->bt_swich.image_nor));
}
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myTitleControlProc 控件主回调函数
*
* @param hwnd
* @param message
* @param wParam
* @param lParam
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int myTitleControlProc (HWND hwnd, int message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PCONTROL pCtrl;
DWORD dwStyle;
MyTitleCtrlInfo* pInfo;
pCtrl = Control (hwnd);
pInfo = (MyTitleCtrlInfo*)pCtrl->dwAddData2;
dwStyle = GetWindowStyle (hwnd);
switch (message) {
case MSG_CREATE:
{
MyTitleCtrlInfo* data = (MyTitleCtrlInfo*)pCtrl->dwAddData;
pInfo = (MyTitleCtrlInfo*) calloc (1, sizeof (MyTitleCtrlInfo));
if (pInfo == NULL)
return -1;
memset(pInfo,0,sizeof(MyTitleCtrlInfo));
pInfo->flag_left = data->flag_left;
pInfo->flag_right = data->flag_right;
strcpy(pInfo->text,data->text);
strcpy(pInfo->text_right,data->text_right);
pInfo->font = data->font;
pInfo->bkg_color= data->bkg_color;
pInfo->font_color= data->font_color;
// 退出按键设置
pInfo->bt_exit.image_nor = &image_exit;
SetRect(&pInfo->bt_exit.rc,16,10,
16 + pInfo->bt_exit.image_nor->bmWidth,
10 + pInfo->bt_exit.image_nor->bmHeight);
// 添加按键设置
pInfo->bt_add.image_nor = &image_add;
SetRect(&pInfo->bt_add.rc,987,10,
987 + pInfo->bt_add.image_nor->bmWidth,
10 + pInfo->bt_add.image_nor->bmHeight);
// 开关按键设置
pInfo->bt_swich.image_nor = &image_swich_off;
pInfo->bt_swich.image_pre = &image_swich_on;
SetRect(&pInfo->bt_swich.rc,974,10,
974 + pInfo->bt_swich.image_nor->bmWidth,
10 + pInfo->bt_swich.image_nor->bmHeight);
pInfo->bt_swich.state = MYTITLE_SWICH_OFF;
pCtrl->dwAddData2 = (DWORD)pInfo;
return 0;
}
case MSG_DESTROY:
free(pInfo);
break;
case MSG_PAINT:
hdc = BeginPaint (hwnd);
paint(hwnd,hdc);
EndPaint (hwnd, hdc);
return 0;
case MSG_MYTITLE_SET_TITLE:
if (wParam)
strcpy(pInfo->text,(char*)wParam);
InvalidateRect (hwnd, NULL, TRUE);
break;
case MSG_MYTITLE_SET_SWICH:
pInfo->bt_swich.state = wParam;
InvalidateRect (hwnd, NULL, TRUE);
break;
case MSG_LBUTTONDOWN:
{
int x, y;
x = LOSWORD(lParam);
y = HISWORD(lParam);
if (GetCapture () == hwnd)
break;
SetCapture (hwnd);
pInfo->click_x = x;
pInfo->click_y = y;
}
break;
case MSG_LBUTTONUP:
{
int x, y;
if (GetCapture() != hwnd) {
// if(pInfo->state!=BUT_NORMAL) {
// pInfo->state = BUT_NORMAL;
// InvalidateRect (hwnd, NULL, TRUE);
// }
break;
}
ReleaseCapture ();
x = LOSWORD(lParam);
y = HISWORD(lParam);
int click_type = clickInButton(pInfo,x,y);
if (click_type) {
NotifyParentEx (hwnd, pCtrl->id, click_type,pInfo->bt_swich.state);
InvalidateRect (hwnd, NULL, TRUE);
}
} break;
default:
break;
}
return DefaultControlProc (hwnd, message, wParam, lParam);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief bmpsMainTitleLoad 加载主界面图片
*
* @param controls
**/
/* ---------------------------------------------------------------------------*/
static void myTitleBmpsLoad(void *ctrls,char *path)
{
bmpsLoad(base_bmps);
}
static void myTitleBmpsRelease(void *ctrls)
{
}
/* ---------------------------------------------------------------------------*/
/**
* @brief createMyTitle 创建单个静态控件
*
* @param hWnd
* @param id
* @param x,y,w,h 坐标
* @param image_normal 正常图片
* @param image_press 按下图片
* @param display 是否显示 0不显示 1显示
* @param mode 是否为选择模式 0非选择 1选择
* @param notif_proc 回调函数
*/
/* ---------------------------------------------------------------------------*/
HWND createMyTitle(HWND hWnd,MyCtrlTitle *ctrl)
{
HWND hCtrl;
MyTitleCtrlInfo pInfo;
pInfo.flag_left = ctrl->flag_left;
pInfo.flag_right = ctrl->flag_right;
if (ctrl->text)
strcpy(pInfo.text,ctrl->text);
if (ctrl->text_right)
strcpy(pInfo.text_right,ctrl->text_right);
pInfo.font = ctrl->font;
pInfo.bkg_color= ctrl->bkg_color;
pInfo.font_color= ctrl->font_color;
hCtrl = CreateWindowEx(CTRL_NAME,"",WS_VISIBLE|WS_CHILD,WS_EX_TRANSPARENT,
ctrl->idc,ctrl->x,ctrl->y,ctrl->w,ctrl->h, hWnd,(DWORD)&pInfo);
if(ctrl->notif_proc) {
SetNotificationCallback (hCtrl, ctrl->notif_proc);
}
return hCtrl;
}
void initMyTitle(void)
{
my_title = (MyControls *)malloc(sizeof(MyControls));
my_title->regist = myTitleRegist;
my_title->unregist = myTitleCleanUp;
my_title->bmpsLoad = myTitleBmpsLoad;
my_title->bmpsRelease = myTitleBmpsRelease;
my_title->bmpsLoad(NULL,NULL);
}
<file_sep>/src/app/video/process/face_process.cpp
/*
* =============================================================================
*
* Filename: face_process.c
*
* Description: 摄像头数据流接口
*
* Version: 1.0
* Created: 2019-06-19 11:50:19
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include "face_process.h"
#include "thread_helper.h"
#include "my_face.h"
#include "debug.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define IAMGE_MAX_W 1280
#define IAMGE_MAX_H 720
#define IMAGE_MAX_DATA (IAMGE_MAX_W * IAMGE_MAX_H * 3 / 2 )
enum {
TYPE_GET_FACE, // 人脸识别
TYPE_GET_CAPTURE, // 抓拍
TYPE_GET_RECORD, // 录像
};
typedef struct _CammerData {
int get_data_end;
int type;
int w,h;
char data[IMAGE_MAX_DATA];
}CammerData;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static CammerData camm_info;
static pthread_mutex_t mutex; //队列控制互斥信号
//#define TEST_WRITE_SP_TO_FILE
static void* faceProcessThread(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
FaceProcess *process = (FaceProcess *)arg;
int ret = 0;
while (process->start_enc() == true) {
if (camm_info.get_data_end == 0) {
usleep(10000);
continue;
}
if (my_face){
ret = my_face->recognizer(camm_info.data,camm_info.w,camm_info.h);
}
pthread_mutex_lock(&mutex);
camm_info.get_data_end = 0;
pthread_mutex_unlock(&mutex);
if (ret == 0) {
sleep(1);
}
}
return NULL;
}
FaceProcess::FaceProcess()
: StreamPUBase("FaceProcess", true, true)
{
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
}
FaceProcess::~FaceProcess()
{
}
bool FaceProcess::processFrame(std::shared_ptr<BufferBase> inBuf,
std::shared_ptr<BufferBase> outBuf)
{
if (camm_info.get_data_end == 0) {
camm_info.w = inBuf->getWidth();
camm_info.h = inBuf->getHeight();
memcpy(camm_info.data,inBuf->getVirtAddr(),inBuf->getDataSize());
pthread_mutex_lock(&mutex);
camm_info.get_data_end = 1;
pthread_mutex_unlock(&mutex);
}
return true;
}
void FaceProcess::faceInit(void)
{
if (my_face)
my_face->init();
camm_info.get_data_end = 0;
start_enc_ = true;
createThread(faceProcessThread,this);
}
void FaceProcess::faceUnInit(void)
{
if (my_face)
my_face->uninit();
camm_info.get_data_end = 0;
start_enc_ = false;
}
int FaceProcess::faceRegist(void *data)
{
MyFaceRegistData *face_data = (MyFaceRegistData *)data;
if (!my_face)
return -1;
return my_face->regist(face_data);
}
<file_sep>/src/app/udp_talk/udp_talk_protocol.c
/*
* =============================================================================
*
* Filename: protocol_video.c
*
* Description: 太川对讲协议
*
* Version: 1.0
* Created: 2018-12-13 14:28:55
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/prctl.h>
#include "state_machine.h"
#include "udp_talk_protocol.h"
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define DBG_PROTOCOL 1
#if DBG_PROTOCOL > 0
#define DBG_P( ... ) \
do { \
printf("[VIDEO DEBUG]"); \
printf( __VA_ARGS__ ); \
}while(0)
#else
#define DBG_P( ... )
#endif
#define NELEMENTS(array) /* number of elements in an array */ \
(sizeof (array) / sizeof ((array) [0]))
#define LOADFUNC(func) \
do {\
if (in->func)\
priv->func = in->func;\
else\
priv->func = func##Default;\
} while (0)
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
/* 呼叫命令 */
enum {
CMD_CALL, /* CMD_CALL 呼叫 */
CMD_ANSWER, /* CMD_ANSWER 保留,测试时不用 */
CMD_TALK, /* CMD_TALK 摘机,被呼叫方发送该消息 */
CMD_OVER, /* CMD_OVER 挂机 */
CMD_UNLOCK, /* CMD_UNLOCK 开锁 */
CMD_LEAVEWORD, /* 留言 */
CMD_FORTIFY, //
CMD_REPEAL, //
CMD_PICTURE, //
CMD_TEXT, //
CMD_CLOSEAD, //
CMD_MUSICPLAY, //
CMD_MUSICSTOP, //
CMD_CLOSEMEDIA,
CMD_SENDPORT1,
CMD_SHAKEHANDS=0x80, // 呼叫前握手命令
ASW_OK=0x100, //呼叫回复成功
ASW_FAIL, //呼叫回复失败
MNT_OK, //监视成功
MNT_BUSY, //监视忙
MNT_VERFAIL, //监视检验MD5失败
MNT_REFUSE, //
CMD_SENDPORT, //
CMD_TRANSCALL, //转发呼叫命令
CMD_TRANSOVER, //转发呼叫结束命令
CMD_TRANSTALK, //一户多机转发摘机
ASW_NOEXISTS, //用户不存在
ASW_TRANSCALL_PERMITTED=0x0110, //一户多机分机接受呼叫
ASW_TRANSCALL_DENIED=0x0111, //一户多机分机拒绝呼叫
CMD_ELEVATOR_PERMIT=0x0200, //电梯互访
ASW_ELEVATOR_SUCCESS=0x0201, //互访呼梯成功
ASW_ELEVATOR_FAIL=0x0202, //互访呼梯失败
CMD_SHAKEHANDS_ASW=0x300, // 呼叫前握手包应答命令
CMD_OVER_TIMEOUT = 0x400, /* 超时挂机 */
};
// 状态机
enum {
EVENT_SHAKEHANDS, //主动呼叫发送握手
EVENT_SHAKEHANDS_ASW, //对方呼叫返回握手
EVENT_TYPE_CENTER, //类型管理中心
EVENT_TYPE_HM, //类型室内机
EVENT_TYPE_DMK, //类型门口机
EVENT_TYPE_HDMK, //类型门口机
EVENT_DIAL, //拨号
EVENT_CALL, //呼叫
EVENT_TALK, //通话
EVENT_TALK_EX, //作为主机收到分机接听指令
EVENT_RING, //被呼叫
EVENT_RING_EX, //作为分机时被呼叫
EVENT_FAIL_COMM, //失败:连接
EVENT_FAIL_SHAKE, //失败:握手
EVENT_FAIL_BUSY, //失败:正忙
EVENT_FAIL_ABORT, //失败:通话中中断
EVENT_HANGUP, //挂机
};
enum {
ST_IDLE, //空闲
ST_SHAKEHANDS, //主动发送握手状态
ST_SHAKEHANDS_ASW, //对方呼叫已返回握手状态
ST_JUDGE_TYPE, //判断设备类型状态3000还是U9
ST_DIAL, //正在拨号
ST_CALL, //呼叫
ST_TALK, //对讲
ST_RING, //被呼叫,响铃
};
enum {
DO_NO, //不做操作,只改变状态
DO_SHAKEHANDS, //发送握手命令
DO_SHAKEHANDS_ASW, //回复握手命令
DO_JUDGE_TYPE, //监视时判断类型
DO_DIAL, //发送拨号命令
DO_CALL, //发送呼叫命令
DO_TALK, //执行对讲流程
DO_TALK_EX, //分机接听,主机保持转发状态
DO_RING, //执行响铃流程
DO_FAIL_COMM, //执行连接失败
DO_FAIL_SHAKE, //执行握手失败
DO_FAIL_BUSY, //执行正忙失败
DO_FAIL_ABORT, //执行通话中中断
DO_RET_FAIL, //回复失败
DO_HANGUP, //执行挂机命令
};
/* 包头 */
typedef struct
{
unsigned int ID;
unsigned int Size;
unsigned int Type;
}COMMUNICATION;
typedef struct _COMMUNICATION_CALL
{
unsigned int Cmd; //Command
char CallID[16]; //呼叫方编号
char CallName[32]; //呼叫方名称
unsigned int CallType; //Type
unsigned int VideoType; //视频类型,0 H264, 1 Mpeg4
unsigned short VideoWidth; //视频类型 0 320X240 1 352X288 2 640X480 3 720X576
unsigned short VideoHeight; //视频类型 0 320X240 1 352X288 2 640X480 3 720X576
} COMMUNICATION_CALL;
//一户多机主机转发呼叫
typedef struct _TCALLFJ {
unsigned int ID;
unsigned int Size;
unsigned int Type;
unsigned int Cmd; //Command
char CallID[16]; //呼叫方编号
char CallName[32]; //呼叫方名称
unsigned int CallType; //Type
unsigned int VideoType; //视频类型,0 H264, 1 Mpeg4
unsigned short VideoWidth; //视频类型 0 320X240 1 352X288 2 640X480 3 720X576
unsigned short VideoHeight; //视频类型 0 320X240 1 352X288 2 640X480 3 720X576
char CallIP[16]; //呼叫方IP地址
unsigned int CallPort; //呼叫方端口号
unsigned int TransByCenter; //户户对讲通过管理中心转发0:否 1:是
unsigned int CenterIP; //管理中心IP地址
char Add[12]; //保留
} TCALLFJ;
//分机数据结构
typedef struct {
char IP[16];
unsigned int dwIP;
int Port;
int DevType;
unsigned long dwLastTick;
unsigned char bCalling;
unsigned char bTalk;
} TRegisiterDev;
//分机登记
typedef struct
{
unsigned int ID;
unsigned int Size;
unsigned int Type;
char Reserve[32];
} TFJRegStruct;
// 状态机传递参数
typedef struct _STMData {
int flag;
char mCallIP[16];
int device_type;
int device_index;
char ip[16];
int port;
struct _COMMUNICATION_CALL p_call;
struct _TCALLFJ p_call_ex;
struct _VideoTrans *video;
}STMData;
typedef struct _UdpCallCmd {
unsigned int cmd;
void (*proc)(struct _VideoTrans *,
char *ip,int port,char *data); //呼叫对讲协议处理
}UdpCallCmd;
typedef struct _STMDo {
int action;
int (*proc)(struct _VideoTrans *video,STMData *data);
}STMDo;
typedef struct _VideoPriv {
StMachine *st_machine; // 状态机处理
VideoProtoclType pro_type; // 对讲协议类型
TRegisiterDev RegDev[MAXFJCOUNT]; // 分机
int enable; // 使能对讲
int port; // 对讲端口
char *master_ip; // 主机IP
char *room_id; // 终端编号(门牌号)
char *room_name; // 本机终端名称
int packet_id; // 发送包ID
int call_cmd; // 对讲协议命令字 TP_CALL
int device_type; // 发送的设备类型 TYPE_USER
int leave_word; // 是否有未读留言0无 1有
int st_run; //状态机运行状态
int st_run_exit; //状态机退出状态
int time_call; //对讲计时
int time_shake; //握手计时
int time_comm; //通信计时
int dwPeerType; //对讲方的设备类型
int m_CodeType; //视频编码类型
int dwInCameraWidth; //呼入Camera的大小
int dwInCameraHeight; //呼入Camera的大小
char cPeerRoom[32]; //对方名称
char cPeerID[16]; //对方ID
char cPeerIP[16]; //对方IP
int PeerPort; //对方端口
int leave_word_state; //是否在留言状态
int master_trans; //是否主机转发的呼叫指令 1主机转发 0非主机转发
int call_dir; // 0 呼入 1呼出
}VideoPriv;
/*-----------------video trans end----------------*/
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static void videoTransHandleCallTime(VideoTrans *This);
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
VideoTrans *protocol_video = NULL;
static STMData *stm_data = NULL;
static StMachine *video_st_machine_bz;
static StMachine *video_st_machine_u9;
static char *st_debug_ev[] = {
"EVENT_SHAKEHANDS", //主动呼叫发送握手
"EVENT_SHAKEHANDS_ASW", //对方呼叫返回握手
"EVENT_TYPE_CENTER", //类型管理中心
"EVENT_TYPE_HM", //类型室内机
"EVENT_TYPE_DMK", //类型门口机
"EVENT_TYPE_HDMK", //类型门口机
"EVENT_DIAL", //拨号
"EVENT_CALL", //呼叫
"EVENT_TALK", //通话
"EVENT_TALK_EX", //作为主机收到分机接听指令
"EVENT_RING", //被呼叫
"EVENT_RING_EX", //作为分机时被呼叫
"EVENT_FAIL_COMM", //失败:连接
"EVENT_FAIL_SHAKE", //失败:握手
"EVENT_FAIL_BUSY", //失败:正忙
"EVENT_FAIL_ABORT", //失败:通话中中断
"EVENT_HANGUP", //挂机
};
static char *st_debug_st[] = {
"ST_IDLE", //空闲
"ST_SHAKEHANDS", //主动发送握手状态
"ST_SHAKEHANDS_ASW", //对方呼叫已返回握手状态
"ST_JUDGE_TYPE", //判断设备类型状态3000还是U9
"ST_DIAL", //正在拨号
"ST_CALL", //呼叫
"ST_TALK", //对讲
"ST_RING", //被呼叫,响铃
};
static char *st_debug_do[] = {
"DO_NO", //不做操作,只改变状态
"DO_SHAKEHANDS", //发送握手命令
"DO_SHAKEHANDS_ASW", //回复握手命令
"DO_JUDGE_TYPE", //监视时判断类型
"DO_DIAL", //发送拨号命令
"DO_CALL", //发送呼叫命令
"DO_TALK", //执行对讲流程
"DO_TALK_EX", //分机接听,主机保持转发状态
"DO_RING", //执行响铃流程
"DO_FAIL_COMM", //执行连接失败
"DO_FAIL_SHAKE", //执行握手失败
"DO_FAIL_BUSY", //执行正忙失败
"DO_FAIL_ABORT", //执行通话中中断
"DO_RET_FAIL", //回复失败
"DO_HANGUP", //执行挂机命令
};
static StateTableDebug st_debug = {
.ev = st_debug_ev,
.st = st_debug_st,
.todo = st_debug_do,
};
/* ---------------------------------------------------------------------------*/
/**
* @brief 通话状态机
*/
/* ---------------------------------------------------------------------------*/
static StateTable stm_video_state_bz[] = {
{EVENT_SHAKEHANDS, ST_IDLE, ST_SHAKEHANDS, DO_SHAKEHANDS},
{EVENT_SHAKEHANDS_ASW, ST_IDLE, ST_SHAKEHANDS_ASW, DO_SHAKEHANDS_ASW},
{EVENT_SHAKEHANDS_ASW, ST_RING, ST_RING, DO_SHAKEHANDS_ASW},
{EVENT_SHAKEHANDS_ASW, ST_JUDGE_TYPE, ST_JUDGE_TYPE, DO_SHAKEHANDS_ASW},
{EVENT_SHAKEHANDS_ASW, ST_DIAL, ST_DIAL, DO_SHAKEHANDS_ASW},
{EVENT_SHAKEHANDS_ASW, ST_CALL, ST_CALL, DO_SHAKEHANDS_ASW},
{EVENT_SHAKEHANDS_ASW, ST_TALK, ST_TALK, DO_SHAKEHANDS_ASW},
{EVENT_RING, ST_SHAKEHANDS_ASW, ST_SHAKEHANDS_ASW, DO_JUDGE_TYPE},
{EVENT_TYPE_HM, ST_SHAKEHANDS_ASW, ST_RING, DO_RING},
{EVENT_TYPE_DMK, ST_SHAKEHANDS_ASW, ST_RING, DO_RING},
{EVENT_TYPE_HDMK, ST_SHAKEHANDS_ASW, ST_RING, DO_RING},
{EVENT_DIAL, ST_SHAKEHANDS, ST_DIAL, DO_DIAL},
{EVENT_TYPE_HM, ST_JUDGE_TYPE, ST_IDLE, DO_NO},
{EVENT_TYPE_DMK, ST_JUDGE_TYPE, ST_IDLE, DO_NO},
{EVENT_TYPE_HDMK, ST_JUDGE_TYPE, ST_IDLE, DO_NO},
{EVENT_DIAL, ST_IDLE, ST_DIAL, DO_DIAL},
{EVENT_RING_EX, ST_IDLE, ST_RING, DO_RING},
{EVENT_RING, ST_IDLE, ST_JUDGE_TYPE, DO_JUDGE_TYPE},
{EVENT_RING, ST_DIAL, ST_DIAL, DO_RET_FAIL},
{EVENT_RING, ST_CALL, ST_CALL, DO_RET_FAIL},
{EVENT_RING, ST_TALK, ST_TALK, DO_RET_FAIL},
{EVENT_RING, ST_RING, ST_RING, DO_RET_FAIL},
{EVENT_TYPE_CENTER, ST_JUDGE_TYPE, ST_RING, DO_RING},
{EVENT_CALL, ST_DIAL, ST_CALL, DO_CALL},
{EVENT_TALK, ST_CALL, ST_TALK, DO_TALK},
{EVENT_TALK, ST_RING, ST_TALK, DO_TALK},
{EVENT_TALK_EX, ST_RING, ST_TALK, DO_TALK_EX},
{EVENT_FAIL_COMM, ST_DIAL, ST_IDLE, DO_FAIL_COMM},
{EVENT_FAIL_COMM, ST_SHAKEHANDS, ST_IDLE, DO_FAIL_COMM},
{EVENT_FAIL_BUSY, ST_DIAL, ST_IDLE, DO_FAIL_BUSY},
{EVENT_FAIL_SHAKE, ST_SHAKEHANDS, ST_IDLE, DO_FAIL_SHAKE},
{EVENT_FAIL_SHAKE, ST_SHAKEHANDS_ASW, ST_IDLE, DO_FAIL_SHAKE},
{EVENT_FAIL_ABORT, ST_CALL, ST_IDLE, DO_FAIL_ABORT},
{EVENT_FAIL_ABORT, ST_TALK, ST_IDLE, DO_FAIL_ABORT},
{EVENT_FAIL_ABORT, ST_RING, ST_IDLE, DO_FAIL_ABORT},
{EVENT_HANGUP, ST_SHAKEHANDS, ST_IDLE, DO_HANGUP},
{EVENT_HANGUP, ST_SHAKEHANDS_ASW, ST_IDLE, DO_HANGUP},
{EVENT_HANGUP, ST_JUDGE_TYPE, ST_IDLE, DO_HANGUP},
{EVENT_HANGUP, ST_RING, ST_IDLE, DO_HANGUP},
{EVENT_HANGUP, ST_DIAL, ST_IDLE, DO_HANGUP},
{EVENT_HANGUP, ST_CALL, ST_IDLE, DO_HANGUP},
{EVENT_HANGUP, ST_TALK, ST_IDLE, DO_HANGUP},
};
static StateTable stm_video_state_u9[] = {
{EVENT_TYPE_HM, ST_JUDGE_TYPE, ST_RING, DO_RING},
{EVENT_TYPE_DMK, ST_JUDGE_TYPE, ST_RING, DO_RING},
{EVENT_TYPE_HDMK, ST_JUDGE_TYPE, ST_RING, DO_RING},
{EVENT_DIAL, ST_IDLE, ST_DIAL, DO_DIAL},
{EVENT_RING_EX, ST_IDLE, ST_RING, DO_RING},
{EVENT_RING, ST_IDLE, ST_JUDGE_TYPE, DO_JUDGE_TYPE},
{EVENT_RING, ST_DIAL, ST_DIAL, DO_RET_FAIL},
{EVENT_RING, ST_CALL, ST_CALL, DO_RET_FAIL},
{EVENT_RING, ST_TALK, ST_TALK, DO_RET_FAIL},
{EVENT_RING, ST_RING, ST_RING, DO_RET_FAIL},
{EVENT_TYPE_CENTER, ST_JUDGE_TYPE, ST_RING, DO_RING},
{EVENT_CALL, ST_DIAL, ST_CALL, DO_CALL},
{EVENT_TALK, ST_CALL, ST_TALK, DO_TALK},
{EVENT_TALK, ST_RING, ST_TALK, DO_TALK},
{EVENT_TALK_EX, ST_RING, ST_TALK, DO_TALK_EX},
{EVENT_FAIL_COMM, ST_DIAL, ST_IDLE, DO_FAIL_COMM},
{EVENT_FAIL_COMM, ST_SHAKEHANDS, ST_IDLE, DO_FAIL_COMM},
{EVENT_FAIL_BUSY, ST_DIAL, ST_IDLE, DO_FAIL_BUSY},
{EVENT_FAIL_SHAKE, ST_SHAKEHANDS, ST_IDLE, DO_FAIL_SHAKE},
{EVENT_FAIL_SHAKE, ST_SHAKEHANDS_ASW, ST_IDLE, DO_FAIL_SHAKE},
{EVENT_FAIL_ABORT, ST_CALL, ST_IDLE, DO_FAIL_ABORT},
{EVENT_FAIL_ABORT, ST_TALK, ST_IDLE, DO_FAIL_ABORT},
{EVENT_FAIL_ABORT, ST_RING, ST_IDLE, DO_FAIL_ABORT},
{EVENT_HANGUP, ST_SHAKEHANDS, ST_IDLE, DO_HANGUP},
{EVENT_HANGUP, ST_SHAKEHANDS_ASW, ST_IDLE, DO_HANGUP},
{EVENT_HANGUP, ST_JUDGE_TYPE, ST_IDLE, DO_HANGUP},
{EVENT_HANGUP, ST_RING, ST_IDLE, DO_HANGUP},
{EVENT_HANGUP, ST_DIAL, ST_IDLE, DO_HANGUP},
{EVENT_HANGUP, ST_CALL, ST_IDLE, DO_HANGUP},
{EVENT_HANGUP, ST_TALK, ST_IDLE, DO_HANGUP},
};
/* ---------------------------------------------------------------------------*/
/**
* @brief sendCmd 发送主动呼叫命令
*
* @param IP 对方IP
* @param Port 对方端口
* @param Cmd 呼叫指令
* @param bCallBack 呼叫结果是否有回调函数
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int sendCmd(VideoTrans * This,
char *IP, int Port,
int Cmd,
int bCallBack)
{
char cBuf[sizeof(COMMUNICATION)+sizeof(COMMUNICATION_CALL)];
COMMUNICATION * pComm = (COMMUNICATION *)cBuf;
COMMUNICATION_CALL *pCall = (COMMUNICATION_CALL *)&cBuf[sizeof(COMMUNICATION)];
pComm->ID = This->priv->packet_id++;
pComm->Size = sizeof(COMMUNICATION)+sizeof(COMMUNICATION_CALL);
pComm->Type = This->priv->call_cmd;
pCall->Cmd = Cmd;
strncpy(pCall->CallID,This->priv->room_id,sizeof(pCall->CallID)-1);
strncpy(pCall->CallName,This->priv->room_name,sizeof(pCall->CallName)-1);
pCall->CallType = This->priv->device_type;
pCall->VideoType = 0;
pCall->VideoWidth = This->priv->dwInCameraWidth;
pCall->VideoHeight = This->priv->dwInCameraHeight;
This->interface->udpSend(This,
IP, Port, cBuf, pComm->Size, bCallBack);
return 1;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief sendCmdRevert 发送对方呼叫命令的回应
*
* @param IP 对方IP
* @param Port 对方端口
* @param Cmd 回应的命令
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int sendCmdRevert(VideoTrans * This,
char *IP,
int Port,
int Cmd)
{
char cBuf[sizeof(COMMUNICATION)+sizeof(COMMUNICATION_CALL)+4];
COMMUNICATION * pComm = (COMMUNICATION *)cBuf;
COMMUNICATION_CALL *pRevert = (COMMUNICATION_CALL *)&cBuf[sizeof(COMMUNICATION)];
memset(cBuf,0,sizeof(COMMUNICATION)+sizeof(COMMUNICATION_CALL)+4);
pComm->ID = This->priv->packet_id++;
pComm->Size = sizeof(COMMUNICATION)+sizeof(COMMUNICATION_CALL);
pComm->Type = This->priv->call_cmd;
pRevert->Cmd = Cmd;
pRevert->CallType = This->priv->device_type;
pRevert->VideoType = 0;
pRevert->VideoWidth = This->priv->dwInCameraWidth;
pRevert->VideoHeight = This->priv->dwInCameraHeight;
strncpy(pRevert->CallID,This->priv->room_id,sizeof(pRevert->CallID)-1);
strncpy(pRevert->CallName,This->priv->room_name,sizeof(pRevert->CallName)-1);
This->interface->udpSend(This,IP,Port,cBuf,pComm->Size,0);
return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief videoCallbackOvertime 呼叫回调函数,呼叫超时时调用
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void videoCallbackOvertime(VideoTrans *This)
{
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
stm_data->flag = 0;
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_FAIL_COMM,stm_data);
DBG_P("[%s]Call Time out, Failed!\n",__FUNCTION__);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief callbackRtp 传输视频时中断超时回调函数
*/
/* ---------------------------------------------------------------------------*/
void callbackRtp(void)
{
// TODO
// VideoTrans * This = &video;
// stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
// sizeof(STMData));
// stm_data->flag = 3;
// This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_FAIL_ABORT,stm_data);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief videoTransMulitDevSendOver 挂断分机
*
* @param This
* @param bTalkOver 1 分机接听,挂断其他分机 0 挂断所有分机
*/
/* ---------------------------------------------------------------------------*/
static void videoTransMulitDevSendOver(VideoTrans *This,int bTalkOver)
{
int i;
if(This->priv->master_ip[0] != 0)
return;
struct _TCALLFJ TransCall;
memset(&TransCall,0,sizeof(TCALLFJ));
TransCall.ID = This->priv->packet_id++;
TransCall.Size = sizeof(TCALLFJ);
TransCall.Type = This->priv->call_cmd;
TransCall.Cmd = CMD_TRANSOVER;
strncpy(TransCall.CallIP,This->priv->cPeerIP,15);
TransCall.CallPort = This->priv->PeerPort;
for(i=0;i<MAXFJCOUNT;i++) {
if(This->priv->RegDev[i].bCalling && (!bTalkOver || !This->priv->RegDev[i].bTalk)) {
This->priv->RegDev[i].bCalling = FALSE;
This->priv->RegDev[i].bTalk = FALSE;
// DBG_P("[%s]:over:%d,%s\n", __FUNCTION__,bTalkOver,This->priv->RegDev[i].IP);
This->interface->udpSend(This,This->priv->RegDev[i].IP,This->priv->RegDev[i].Port,
&TransCall,sizeof(TCALLFJ),0);
}
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmDoNothing 不做任何事,只改变状态
*
* @param This
* @param st_data
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int stmDoNothing(VideoTrans * This,STMData *st_data)
{
return CALL_OK;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmJudgeType 判断呼叫来源类型,门口机或室内机
*
* @param This
* @param st_data
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int stmJudgeType(VideoTrans * This,STMData *st_data)
{
DBG_P("STMDO:JudgeType()\n");
char *IP = st_data->ip;
int Port= st_data->port;
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
memcpy(stm_data,st_data,sizeof(STMData));
stm_data->device_index = This->interface->isCenter(This,IP);
stm_data->device_type = EVENT_TYPE_CENTER;
if (stm_data->device_index != -1 ) {
if (This->priv->pro_type == VIDEOTRANS_PROTOCOL_3000)
sendCmdRevert(This,IP,Port,CMD_SHAKEHANDS); //通知管理中心使用3000协议
goto judge_end;
}
stm_data->device_index = This->interface->isDmk(This,IP);
stm_data->device_type = EVENT_TYPE_DMK;
if (stm_data->device_index != -1 )
goto judge_end;
stm_data->device_index = This->interface->isHDmk(This,IP);
stm_data->device_type = EVENT_TYPE_HDMK;
if (stm_data->device_index != -1 )
goto judge_end;
stm_data->device_type = EVENT_TYPE_HM;
judge_end:
This->priv->st_machine->msgPost(This->priv->st_machine,
stm_data->device_type,
stm_data);
return CALL_OK;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmCallIP 直接呼叫IP
* 如果成功,视设置需要转输音频至对方,但不传输音频
* @param This
* @param IP 对方IP
* @param Port 对方端口
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int stmCallIP(VideoTrans * This,STMData *st_data)
{
DBG_P("STMDO:CallIP():%s\n",st_data->mCallIP);
This->priv->PeerPort = This->priv->port;
strcpy(This->priv->cPeerIP,st_data->mCallIP);
sendCmd(This,This->priv->cPeerIP,This->priv->port,CMD_CALL,TRUE);
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_CALLIP);
This->priv->time_comm = COMM_TIME;
return CALL_OK;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmShakeHands 呼叫对讲前的握手命令
* 在使用3000协议对讲时需要增加握手协议,以区别U9协议,2者互不能通信
* 在呼叫管理中心时,需要先发握手,不需等回应,再发呼叫
*
* @param This
* @param IP 对方IP
* @param Port 对方端口
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int stmShakeHands(VideoTrans * This,STMData *st_data)
{
DBG_P("STMDO:ShakeHands()\n");
strcpy(This->priv->cPeerIP,st_data->mCallIP);
sendCmd(This,This->priv->cPeerIP,This->priv->port,CMD_SHAKEHANDS,TRUE);
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_SHAKEHANDS);
This->priv->time_shake = SHAKE_TIME;
return CALL_OK;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmShakeHandsRet 呼叫对讲前的握手命令返回
* 在使用3000协议对讲时需要增加握手协议,以区别U9协议,2者互不能通信
*
* @param This
* @param IP 对方IP
* @param Port 对方端口
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int stmShakeHandsRet(VideoTrans * This,STMData *st_data)
{
DBG_P("STMDO:ShakeHandsRet()\n");
sendCmdRevert(This,st_data->ip,st_data->port,CMD_SHAKEHANDS_ASW);
This->priv->time_shake = SHAKE_TIME;
return CALL_OK;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmRetCall 返回呼叫的结果
*
* @param This
* @param RetCode ASW_OK 呼叫成功,开始建立RTP连接传输音频,但不传输
* 视频
* ASW_FAIL 呼叫失败,说明对方在线,但出于正忙状态
*/
/* ---------------------------------------------------------------------------*/
static int stmRetCall(VideoTrans *This,STMData *st_data)
{
DBG_P("STMDO:RetIP():w:%d,h:%d\n",
st_data->p_call.VideoWidth,st_data->p_call.VideoHeight);
This->priv->dwInCameraWidth = st_data->p_call.VideoWidth;
This->priv->dwInCameraHeight = st_data->p_call.VideoHeight;
This->priv->time_call = RING_TIME;
int index = This->interface->isDmk(This,st_data->ip);
memset(This->priv->cPeerRoom,0,sizeof(This->priv->cPeerRoom));
if (index != -1) {
strncpy(This->priv->cPeerRoom,
This->interface->getDmkName(This,index),
sizeof(This->priv->cPeerRoom)-1);
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_RETCALL_MONITOR);
goto ret_call_end;
}
index = This->interface->isHDmk(This,st_data->ip);
if (index != -1) {
strncpy(This->priv->cPeerRoom,
This->interface->getHDmkName(This,index),
sizeof(This->priv->cPeerRoom)-1);
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_RETCALL_MONITOR);
goto ret_call_end;
}
strncpy(This->priv->cPeerRoom,
st_data->p_call.CallName,
sizeof(This->priv->cPeerRoom)-1);
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_RETCALL);
ret_call_end:
This->priv->call_dir = VIDEOTRANS_CALL_DIR_OUT;
This->interface->saveRecordAsync(This,VIDEOTRANS_CALL_DIR_OUT,
This->priv->cPeerRoom,This->priv->cPeerIP);
return CALL_OK;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmRing 对方主动呼叫,振铃,并显示IP地址,如果对方
* 传输视频,须显示。
* 当为3000系统时,如果是室内机呼叫,需要先接受过握手协议,才响应,
* 如果是管理中心,先回握手协议,再响应
*
*
* @param This
* @param IP 对方IP
* @param Port 对方端口
* @param pCall 相关参数
*
* @returns
// 如果成功,返回非0,失败返回0
*/
/* ---------------------------------------------------------------------------*/
static int stmRing(VideoTrans * This,STMData *st_data)
{
int i;
char *IP = st_data->ip;
int Port= st_data->port;
COMMUNICATION_CALL *pCall = &st_data->p_call;
This->priv->dwInCameraWidth = st_data->p_call.VideoWidth;
This->priv->dwInCameraHeight = st_data->p_call.VideoHeight;
This->priv->m_CodeType = pCall->VideoType;
This->priv->dwPeerType = pCall->CallType;
//设置对方IP,根据IP和端口号发送回复给对方
strcpy(This->priv->cPeerIP,IP);
strncpy(This->priv->cPeerID,pCall->CallID,sizeof(This->priv->cPeerID)-1);
This->priv->PeerPort = This->priv->port;
if (This->priv->master_trans)
sendCmdRevert(This,IP,Port,ASW_TRANSCALL_PERMITTED);
else
sendCmdRevert(This,IP,Port,ASW_OK);
memset(This->priv->cPeerRoom,0,sizeof(This->priv->cPeerRoom));
if (st_data->device_type == EVENT_TYPE_DMK ) {
strncpy(This->priv->cPeerRoom,
This->interface->getDmkName(protocol_video,st_data->device_index),
sizeof(This->priv->cPeerRoom)-1);
} else if (st_data->device_type == EVENT_TYPE_HDMK ) {
strncpy(This->priv->cPeerRoom,
This->interface->getHDmkName(protocol_video,st_data->device_index),
sizeof(This->priv->cPeerRoom)-1);
} else {
strncpy(This->priv->cPeerRoom,
pCall->CallName,
sizeof(This->priv->cPeerRoom)-1);
}
// 转发到分机-------
uint64_t dwTick = This->interface->getSystemTick(This);
TCALLFJ TransCall;
memcpy(&(TransCall.Cmd),pCall,sizeof(COMMUNICATION_CALL));
TransCall.ID = This->priv->packet_id++;
TransCall.Size = sizeof(TCALLFJ);
TransCall.Type = This->priv->call_cmd;
TransCall.Cmd = CMD_TRANSCALL;
strncpy(TransCall.CallIP,IP,15);
TransCall.CallPort = Port;
TransCall.TransByCenter = 0;
TransCall.CenterIP = 0;
for(i=0; i<MAXFJCOUNT; i++) {
if(This->priv->RegDev[i].dwLastTick && This->interface->getDiffSysTick(This,dwTick, This->priv->RegDev[i].dwLastTick) < FJ_REGIST_TIME) {
This->priv->RegDev[i].bCalling = TRUE;
This->interface->udpSend(This,This->priv->RegDev[i].IP,This->priv->RegDev[i].Port,&TransCall,
sizeof(TCALLFJ),0);
} else {
This->priv->RegDev[i].bCalling = FALSE;
}
}
// ----------
This->priv->time_call = RING_TIME;
This->interface->sendMessageStatus(This, VIDEOTRANS_UI_RING);
This->priv->call_dir = VIDEOTRANS_CALL_DIR_IN;
This->interface->saveRecordAsync(This,VIDEOTRANS_CALL_DIR_IN,
This->priv->cPeerRoom,This->priv->cPeerIP);
return CALL_OK;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmAnswer 对方接听,进行通话(传输音频或音视频同时传输)
*
* @param This
* @param IP 对方IP
* @param Port 对方端口
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int stmAnswer(VideoTrans * This,STMData *st_data)
{
DBG_P("STMDO:Answer()\n");
This->priv->PeerPort = This->priv->port;
if(This->priv->leave_word_state) {
This->priv->time_call = LEAVE_WORD_TIME;
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_LEAVE_WORD);
This->priv->leave_word = 1;
} else {
This->priv->time_call = TALK_TIME;
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_ANSWER);
}
if (This->priv->master_trans) {
TCALLFJ Packet;
memset(&Packet,0,sizeof(TCALLFJ));
Packet.ID = This->priv->packet_id++;
Packet.Size = sizeof(TCALLFJ);
Packet.Type = This->priv->call_cmd;
Packet.Cmd = CMD_TRANSTALK;
This->interface->udpSend(This,This->priv->cPeerIP,This->priv->PeerPort,&Packet,Packet.Size,0);
} else {
sendCmd(This,
This->priv->cPeerIP,
This->priv->PeerPort,
CMD_TALK,
FALSE);
}
videoTransMulitDevSendOver(This,FALSE);
return TRUE;
}
static int stmAnswerEx(VideoTrans * This,STMData *st_data)
{
DBG_P("STMDO:AnswerEx()\n");
int i;
char *IP = st_data->ip;
for(i=0;i<MAXFJCOUNT;i++) {
if(strcmp(This->priv->RegDev[i].IP,IP)!=0 || !This->priv->RegDev[i].bCalling)
continue;
DBG_P("[%s]:%s\n", __FUNCTION__,This->priv->RegDev[i].IP);
sendCmd(This,
This->priv->cPeerIP,
This->priv->PeerPort,
CMD_TALK,
FALSE);
This->priv->time_call = TALK_TIME;
This->priv->RegDev[i].bTalk = TRUE;
//挂断其它分机
videoTransMulitDevSendOver(This,TRUE);
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_ANSWER_EX);
break;
}
return TRUE;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmRetFail 通话中有被监视,返回失败
*
* @param This
* @param st_data
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int stmRetFail(VideoTrans * This,STMData *st_data)
{
DBG_P("STMDO:RetFail()\n");
sendCmdRevert(This,st_data->ip,st_data->port,ASW_FAIL);
return CALL_OK;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmOver 结束对讲
*
* @param This
* @param ByMyself 2超时或非正常挂机(对方返回忙或通话过程断线) 1本机主动按键挂机,0远程发起命令结束
*/
/* ---------------------------------------------------------------------------*/
static int stmOver(VideoTrans * This,STMData *st_data)
{
DBG_P("STMDO:Over():ByMyself:%d\n",st_data->flag);
int ByMyself = st_data->flag;
This->priv->leave_word_state = FALSE;
This->priv->time_call = 0;
This->priv->master_trans = 0;
if(ByMyself) {
sendCmd(This,
This->priv->cPeerIP,
This->priv->PeerPort,
CMD_OVER,
FALSE);
}
videoTransMulitDevSendOver(This,FALSE);
memset(This->priv->cPeerRoom,0,sizeof(This->priv->cPeerRoom));
This->priv->cPeerIP[0] = 0;
This->priv->PeerPort = 0;
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_OVER);
DBG_P("stmOver\n");
return CALL_OK;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief stmFail 返回失败
*
* @param This
* @param st_data
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int stmFail(VideoTrans * This,STMData *st_data)
{
DBG_P("STMDO:Fail(),type:%d\n",st_data->flag);
int type = st_data->flag;
if (type == 0) {
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_FAILCOMM);
} else if (type == 1) {
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_FAILSHAKEHANDS);
} else if (type == 2) {
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_FAILBUSY);
} else if (type == 3) {
st_data->flag = 1;
stmOver(This,st_data);
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_FAILABORT);
}
return CALL_OK;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief videoCall 发送呼叫命令
*
* @param This
* @param ip 被呼叫IP
*/
/* ---------------------------------------------------------------------------*/
static void videoCall(VideoTrans *This,char *ip)
{
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
memcpy(stm_data->mCallIP,ip,sizeof(stm_data->mCallIP));
stm_data->device_index = This->interface->isCenter(This,ip);
stm_data->device_type = EVENT_TYPE_CENTER;
if (stm_data->device_index != -1 ) {
// 没获取机身码时不可以呼叫
if (This->priv->enable) {
if (This->priv->pro_type == VIDEOTRANS_PROTOCOL_3000)
sendCmd(This,ip,This->priv->port,CMD_SHAKEHANDS,FALSE);
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_DIAL,stm_data);
This->interface->showCallWindow(This);
} else {
This->interface->showCallWindow(This);
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_FAILABORT);
}
return;
}
stm_data->device_index = This->interface->isDmk(This,ip);
stm_data->device_type = EVENT_TYPE_DMK;
if (stm_data->device_index != -1 )
goto call_end;
stm_data->device_index = This->interface->isHDmk(This,ip);
stm_data->device_type = EVENT_TYPE_HDMK;
if (stm_data->device_index != -1 )
goto call_end;
stm_data->device_type = EVENT_TYPE_HM;
call_end:
if (This->priv->enable) {
if (This->priv->pro_type == VIDEOTRANS_PROTOCOL_3000)
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_SHAKEHANDS,stm_data);
else
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_DIAL,stm_data);
This->interface->showCallWindow(This);
} else {
This->interface->showCallWindow(This);
This->interface->sendMessageStatus(This,VIDEOTRANS_UI_FAILABORT);
}
}
static void videoAnswer(VideoTrans *This)
{
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_TALK,0);
}
static void videoLeaveWord(VideoTrans *This)
{
This->priv->leave_word_state = TRUE;
This->answer(This);
}
static void videoHangup(VideoTrans *This)
{
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
stm_data->flag = 1;
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_HANGUP,stm_data);
}
static char *videoGetPeerIP(VideoTrans *This)
{
return This->priv->cPeerIP;
}
static int videoGetTalkPort(VideoTrans *This)
{
return 8800;
}
static int videoGetIdleStatus(VideoTrans *This)
{
if (This->priv->st_machine->getCurrentstate(This->priv->st_machine) == ST_IDLE)
return 1;
else
return 0;
}
static int videoGetTalkStatus(VideoTrans *This)
{
if (This->priv->st_machine->getCurrentstate(This->priv->st_machine) == ST_TALK)
return 1;
else
return 0;
}
static void videosetStatusBusy(VideoTrans *This)
{
This->priv->st_machine->setCurrentstate(This->priv->st_machine,ST_TALK);
}
static void videosetStatusIdle(VideoTrans *This)
{
This->priv->st_machine->setCurrentstate(This->priv->st_machine,ST_IDLE);
}
static void videoUnlock(VideoTrans * This)
{
if (This->priv->st_machine->getCurrentstate(This->priv->st_machine) == ST_IDLE)
return;
sendCmd(This,
This->priv->cPeerIP,
This->priv->PeerPort,
CMD_UNLOCK,
FALSE);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief videoTransDispCallTime 获得当前通话倒计时时间,用于显示与
* 计时
*
* @param This
*
* @returns 通话时间
*/
/* ---------------------------------------------------------------------------*/
static VideoProtocolStatus videoTransDispCallTime(VideoTrans *This,int *disp_time)
{
static int PreTime = 0;
if(This->priv->time_call == PreTime) {
return VIDEOTRANS_STATUS_NULL;
}
*disp_time = PreTime = This->priv->time_call;
switch (This->priv->st_machine->getCurrentstate(This->priv->st_machine))
{
case ST_CALL:
case ST_RING:
return VIDEOTRANS_STATUS_RING;
case ST_TALK:
return VIDEOTRANS_STATUS_TALK;
default :
return VIDEOTRANS_STATUS_NULL;
}
}
static char * videoTransDispCallName(VideoTrans *This)
{
return This->priv->cPeerRoom;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief videoTransHandleCallTime 在1s定时器函数执行,通话时-1
*
* @param This
*
*/
/* ---------------------------------------------------------------------------*/
static void videoTransHandleCallTime(VideoTrans *This)
{
if (!This)
return;
if (This->priv->st_machine->getCurrentstate(This->priv->st_machine) == ST_IDLE)
return;
if(This->priv->time_call) {
This->priv->time_comm = 0;
This->priv->time_shake = 0;
// DBG_P("time_call:%d\n", This->priv->time_call);
if(--This->priv->time_call == 0) {
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
stm_data->flag = 1;
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_HANGUP,stm_data);
return;
}
}
if (This->priv->time_comm) {
This->priv->time_shake = 0;
DBG_P("time_comm:%d\n", This->priv->time_comm);
if (--This->priv->time_comm == 0) {
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
stm_data->flag = 0;
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_FAIL_COMM,stm_data);
}
}
if (This->priv->time_shake) {
DBG_P("time_shake:%d\n", This->priv->time_shake);
if (--This->priv->time_shake == 0) {
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
stm_data->flag = 1;
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_FAIL_SHAKE,stm_data);
}
}
return ;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief videoTransDestroy 销毁对象,退出程序
*
* @param This
*/
/* ---------------------------------------------------------------------------*/
static void videoTransDestroy(VideoTrans * This)
{
This->priv->st_machine->destroy(&This->priv->st_machine);
free(This->interface);
free(This->priv);
free(This);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpCallRing 通话协议:被呼叫
*
* @param This
* @param ABinding
* @param AData
*/
/* ---------------------------------------------------------------------------*/
static void udpCallRing(VideoTrans * This,char *ip,int port,char *data)
{
if (!This->priv->enable)
return;
DBG_P("CMD_CALL:Ring()\n");
COMMUNICATION_CALL *pCall = (COMMUNICATION_CALL *)&data[sizeof(COMMUNICATION)];
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
strcpy(stm_data->ip,ip);
stm_data->port = port;
memcpy(&stm_data->p_call,pCall,sizeof(COMMUNICATION_CALL));
This->priv->master_trans = 0;
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_RING,stm_data);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpCallRingEx 作为分机时被呼叫
*
* @param This
* @param ABinding
* @param AData
*/
/* ---------------------------------------------------------------------------*/
static void udpCallRingEx(VideoTrans * This,char *ip,int port,char *data)
{
DBG_P("CMD_TRANSCALL:RingEx()\n");
TCALLFJ *pCall = (TCALLFJ *)data;
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
strcpy(stm_data->ip,ip);
stm_data->port = port;
memcpy(&stm_data->p_call_ex,pCall,sizeof(TCALLFJ));
This->priv->master_trans = 1;
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_RING_EX,data);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpCallTalk 通话协议:对方接听
*
* @param This
* @param ABinding
* @param AData
*/
/* ---------------------------------------------------------------------------*/
static void udpCallTalk(VideoTrans * This,char *ip,int port,char *data)
{
DBG_P("CMD_TALK:Answer()\n");
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_TALK,0);
}
static void udpCallTalkEx(VideoTrans * This,char *ip,int port,char *data)
{
DBG_P("CMD_TRANSTALK:AnswerEx()\n");
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
strcpy(stm_data->ip,ip);
stm_data->port = port;
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_TALK_EX,stm_data);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpCallUnlock 作为主机时,分机通话中开锁,主机转发开锁命令
*
* @param This
* @param ABinding
* @param AData
*/
/* ---------------------------------------------------------------------------*/
static void udpCallUnlock(VideoTrans * This,char *ip,int port,char *data)
{
DBG_P("CMD_UNLOCK()\n");
if(This->priv->master_ip[0] != 0)
return;
int i;
for(i=0; i<MAXFJCOUNT; i++) {
if(strcmp(ip,This->priv->RegDev[i].IP) == 0) {
DBG_P("[%s]:%s\n", __FUNCTION__,This->priv->RegDev[i].IP);
This->unlock(This);
}
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpCallOver 通话协议:对方挂机
*
* @param This
* @param ABinding
* @param AData
*/
/* ---------------------------------------------------------------------------*/
static void udpCallOver(VideoTrans * This,char *ip,int port,char *data)
{
DBG_P("CMD_OVER:Over():%s\n", ip);
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
if (strcmp(ip,This->priv->cPeerIP) == 0)
stm_data->flag = 0;
else
stm_data->flag = 1;
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_HANGUP,stm_data);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpCallAswOk 通话协议:呼叫后对方应答OK
*
* @param This
* @param ABinding
* @param AData
*/
/* ---------------------------------------------------------------------------*/
static void udpCallAswOk(VideoTrans * This,char *ip,int port,char *data)
{
DBG_P("CMD_ASW_OK:RetCall()IP:%s\n",ip);
if (strcmp(ip,This->priv->cPeerIP) == 0){
COMMUNICATION_CALL *pCall = (COMMUNICATION_CALL *)&data[sizeof(COMMUNICATION)];
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
strcpy(stm_data->ip,ip);
stm_data->port = port;
memcpy(&stm_data->p_call,pCall,sizeof(COMMUNICATION_CALL));
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_CALL,stm_data);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpCallAswFail 通话协议:呼叫后对方应答失败(正忙)
*
* @param This
* @param ABinding
* @param AData
*/
/* ---------------------------------------------------------------------------*/
static void udpCallAswFail(VideoTrans * This,char *ip,int port,char *data)
{
DBG_P("CMD_ASW_FAIL:RetFail()IP:%s\n",ip);
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
stm_data->flag = 2;
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_FAIL_BUSY,stm_data);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpCallShakeHands 通话协议:对方发送握手协议
*
* @param This
* @param ABinding
* @param AData
*/
/* ---------------------------------------------------------------------------*/
static void udpCallShakeHands(VideoTrans * This,char *ip,int port,char *data)
{
if (This->priv->pro_type != VIDEOTRANS_PROTOCOL_3000)
return;
DBG_P("CMD_SHAKEHANDS :shakeHandsRet()\n");
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
strcpy(stm_data->ip,ip);
stm_data->port = port;
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_SHAKEHANDS_ASW,stm_data);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpCallShakeHandsAsw 通话协议:对方应答握手协议
*
* @param This
* @param ABinding
* @param AData
*/
/* ---------------------------------------------------------------------------*/
static void udpCallShakeHandsAsw(VideoTrans * This,char *ip,int port,char *data)
{
if (This->priv->pro_type != VIDEOTRANS_PROTOCOL_3000)
return;
DBG_P("CMD_SHAKEHANDS_ASW :CallIP():%s\n",ip);
stm_data = (STMData *)This->priv->st_machine->initPara(This->priv->st_machine,
sizeof(STMData));
memcpy(stm_data->mCallIP,ip,sizeof(stm_data->mCallIP));
This->priv->st_machine->msgPost(This->priv->st_machine,EVENT_DIAL,stm_data);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief udpCallDenied 通话协议:作为主机时分机拒绝接听
*
* @param This
* @param ABinding
* @param AData
*/
/* ---------------------------------------------------------------------------*/
static void udpCallDenied(VideoTrans * This,char *ip,int port,char *data)
{
DBG_P("ASW_TRANSCALL_DENIED()\n");
int i;
for(i=0;i<MAXFJCOUNT;i++) {
if( strcmp(ip,This->priv->RegDev[i].IP) == 0
&& This->priv->RegDev[i].bCalling) {
DBG_P("[%s]:%s\n", __FUNCTION__,This->priv->RegDev[i].IP);
This->priv->RegDev[i].bCalling = FALSE;
break;
}
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief 通话状态机执行函数,与枚举顺序一致
*/
/* ---------------------------------------------------------------------------*/
static STMDo stm_video_state_do[] = {
{DO_NO, stmDoNothing},
{DO_SHAKEHANDS, stmShakeHands},
{DO_SHAKEHANDS_ASW, stmShakeHandsRet},
{DO_JUDGE_TYPE, stmJudgeType},
{DO_DIAL, stmCallIP},
{DO_CALL, stmRetCall},
{DO_TALK, stmAnswer},
{DO_TALK_EX, stmAnswerEx},
{DO_RING, stmRing},
{DO_FAIL_COMM, stmFail},
{DO_FAIL_SHAKE, stmFail},
{DO_FAIL_BUSY, stmFail},
{DO_FAIL_ABORT, stmFail},
{DO_RET_FAIL, stmRetFail},
{DO_HANGUP, stmOver},
};
/* ---------------------------------------------------------------------------*/
/**
* @brief videoTransSTMHanldeVideo 呼叫流程状态机执行体
*
* @param This
* @param data 传入参数
*/
/* ---------------------------------------------------------------------------*/
static int videoTransSTMHanldeVideo(StMachine *This,int result,void *data,void *arg)
{
STMData *st_data = (STMData *)data;
stm_video_state_do[This->getCurRun(This)].proc(arg,st_data);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief 通话协议处理表
*/
/* ---------------------------------------------------------------------------*/
static UdpCallCmd udp_call_cmd_handle[] = {
{CMD_CALL, udpCallRing},
{CMD_TALK, udpCallTalk},
{CMD_OVER, udpCallOver},
{CMD_UNLOCK, udpCallUnlock},
{ASW_TRANSCALL_DENIED, udpCallDenied},
{ASW_OK, udpCallAswOk},
{ASW_FAIL, udpCallAswFail},
{CMD_SHAKEHANDS, udpCallShakeHands},
{CMD_SHAKEHANDS_ASW, udpCallShakeHandsAsw},
};
static UdpCallCmd udp_call_ex_cmd_handle[] = {
{CMD_TRANSCALL, udpCallRingEx},
{CMD_TRANSTALK, udpCallTalkEx},
{CMD_TRANSOVER, udpCallOver},
};
/* ---------------------------------------------------------------------------*/
/**
* @brief udpCallHandle 通话协议处理
*
* @param This
* @param ABinding
* @param AData
*/
/* ---------------------------------------------------------------------------*/
static void udpCallHandle(VideoTrans *This,
char *ip,int port, char *data,int size)
{
if(size == sizeof(COMMUNICATION) + sizeof(COMMUNICATION_CALL)) {
COMMUNICATION_CALL *pCall = (COMMUNICATION_CALL *)&data[sizeof(COMMUNICATION)];
unsigned int i;
for(i=0; i<NELEMENTS(udp_call_cmd_handle); i++) {
if (udp_call_cmd_handle[i].cmd == pCall->Cmd) {
udp_call_cmd_handle[i].proc(This,ip,port,data);
return;
}
}
DBG_P("[%s] : call cmd = 0x%04x\n",__FUNCTION__,pCall->Cmd);
} else if(size == sizeof(TCALLFJ)) {
DBG_P("From :%s-->",ip);
TCALLFJ *pCallFJ = (TCALLFJ*)data;
unsigned int i;
for(i=0; i<NELEMENTS(udp_call_ex_cmd_handle); i++) {
if (udp_call_ex_cmd_handle[i].cmd == pCallFJ->Cmd) {
udp_call_ex_cmd_handle[i].proc(This,ip,port,data);
return;
}
}
}
}
static void *videoTimerThread(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
while (1) {
videoTransHandleCallTime(arg);
sleep(1);
}
return NULL;
}
static void videoTimerThreadCreate(VideoTrans *arg)
{
int result;
pthread_t m_pthread; //线程号
pthread_attr_t threadAttr1; //线程属性
pthread_attr_init(&threadAttr1); //附加参数
//设置线程为自动销毁
pthread_attr_setdetachstate(&threadAttr1,PTHREAD_CREATE_DETACHED);
result = pthread_create(&m_pthread,&threadAttr1,videoTimerThread,arg);
if(result) {
DBG_P("[%s] pthread failt,Error code:%d\n",__FUNCTION__,result);
}
pthread_attr_destroy(&threadAttr1); //释放附加参数
}
static int videoGetLeaveWord(VideoTrans *This)
{
return This->priv->leave_word;
}
static void videoClearLeaveWord(VideoTrans *This)
{
This->priv->leave_word = 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief videoTransResetProtocol 切换协议时,重新创建状态机线程
*
* @param This
* @param type 协议类型
*/
/* ---------------------------------------------------------------------------*/
static void videoTransResetProtocol(VideoTrans *This,VideoProtoclType type)
{
This->priv->st_run = 0;
while (This->priv->st_run_exit == 0) {
usleep(10000);
}
if (This->priv->pro_type == VIDEOTRANS_PROTOCOL_3000) {
This->priv->st_machine = video_st_machine_bz;
} else {
This->priv->st_machine = video_st_machine_u9;
}
This->priv->pro_type = type;
}
static void videoEnable(VideoTrans *This)
{
This->priv->enable = 1;
}
static void videoRegistDev(VideoTrans *This,char *ip,int port,int type,char *data)
{
if(This->priv->master_ip[0] != 0)
return;
TFJRegStruct *reg = (TFJRegStruct *)data;
//主机
uint64_t dwTick = This->interface->getSystemTick(This);
int i,FreeIdx = -1;
for(i=0; i<MAXFJCOUNT; i++) {
if(strcmp(ip,This->priv->RegDev[i].IP)==0)
break;
if( (FreeIdx == -1)
&& ( (This->priv->RegDev[i].dwLastTick == 0)
|| (This->interface->getDiffSysTick(This,dwTick, This->priv->RegDev[i].dwLastTick) > FJ_REGIST_TIME)) ) {
FreeIdx = i;
}
}
if (i == MAXFJCOUNT) {
if(FreeIdx != -1) {
strncpy(This->priv->RegDev[FreeIdx].IP,ip,15);
This->priv->RegDev[FreeIdx].dwIP = inet_addr(ip);
// printf("UDPDevRegProc[%d] ABIP:%s Ip:%s,dwIP:%d\n",
// FreeIdx,ABinding->IP,Public.RegDev[FreeIdx].IP, Public.RegDev[FreeIdx].dwIP);
This->priv->RegDev[FreeIdx].Port = port;
This->priv->RegDev[FreeIdx].DevType = reg->Type==type? 1 : 0;
This->priv->RegDev[FreeIdx].dwLastTick = dwTick;
}
} else {
This->priv->RegDev[i].Port = port;
This->priv->RegDev[i].DevType = reg->Type==type? 1 : 0;
This->priv->RegDev[i].dwLastTick = dwTick;
}
}
static void videoRegistToMaster(VideoTrans *This,int type)
{
TFJRegStruct Packet;
memset(&Packet,0,sizeof(TFJRegStruct));
Packet.ID = 0;
Packet.Size = sizeof(TFJRegStruct);
Packet.Type = type;
This->interface->udpSend(This,
This->priv->master_ip,This->priv->port,&Packet,Packet.Size,
0);
}
static void *videoGetRegistDev(struct _VideoTrans *This)
{
return This->priv->RegDev;
}
static char *videoGetRegistOneDevIp(struct _VideoTrans *This,int index)
{
return This->priv->RegDev[index].IP;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief getSystemTickDefault 接口默认函数
*
* @param This
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static uint64_t getSystemTickDefault(struct _VideoTrans *This)
{
DBG_P("[%s]\n", __FUNCTION__);
return 0;
}
static uint64_t getDiffSysTickDefault(struct _VideoTrans *This,
uint64_t cur,uint64_t oldThis)
{
DBG_P("[%s]\n", __FUNCTION__);
return 0;
}
static void sendMessageStatusDefault(VideoTrans *This,VideoUiStatus status)
{
DBG_P("[%s]:%d\n", __FUNCTION__,status);
}
static void showCallWindowDefault(VideoTrans *This)
{
DBG_P("[%s]\n", __FUNCTION__);
}
static void udpSendDefault(struct _VideoTrans *This,
char *ip,int port,void *data,int size, int enable_call_back)
{
DBG_P("[%s]\n", __FUNCTION__);
}
static void saveRecordAsyncDefault(struct _VideoTrans *This,VideoCallDir dir,char *name,char *ip)
{
DBG_P("[%s]\n", __FUNCTION__);
}
static int isCenterDefault(struct _VideoTrans *This,char *ip)
{
DBG_P("[%s]\n", __FUNCTION__);
return -1;
}
static int isDmkDefault(struct _VideoTrans *This,char *ip)
{
DBG_P("[%s]\n", __FUNCTION__);
return -1;
}
static int isHDmkDefault(struct _VideoTrans *This,char *ip)
{
DBG_P("[%s]\n", __FUNCTION__);
return -1;
}
static char *getDmkNameDefault(struct _VideoTrans *This,int index)
{
DBG_P("[%s]\n", __FUNCTION__);
return "dmk default";
}
static char *getHDmkNameDefault(struct _VideoTrans *This,int index)
{
DBG_P("[%s]\n", __FUNCTION__);
return "hdmk default";
}
static void loadInterface( VideoInterface *priv,VideoInterface *in)
{
LOADFUNC(getSystemTick);
LOADFUNC(getDiffSysTick);
LOADFUNC(udpSend);
LOADFUNC(saveRecordAsync);
LOADFUNC(sendMessageStatus);
LOADFUNC(showCallWindow);
LOADFUNC(isCenter);
LOADFUNC(isDmk);
LOADFUNC(isHDmk);
LOADFUNC(getDmkName);
LOADFUNC(getHDmkName);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief videoTransCreate 创建呼叫对讲对象
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
VideoTrans * videoTransCreate(VideoInterface *interface,
int port,
int call_cmd,
int device_type,
VideoProtoclType type,
char *master_ip,
char *room_name,
char *room_id)
{
VideoTrans * This = (VideoTrans *)calloc(1,sizeof(VideoTrans));
if(This == NULL) {
DBG_P("calloc video fail!\n");
return NULL;
}
This->priv = (VideoPriv *)calloc(1,sizeof(VideoPriv));
if (This->priv == NULL) {
DBG_P("calloc video priv fail!\n");
free(This);
return NULL;
}
This->interface = (VideoInterface *)calloc(1,sizeof(VideoInterface));
if (This->interface == NULL) {
DBG_P("calloc video interface fail!\n");
free(This->priv);
free(This);
return NULL;
}
This->priv->packet_id = (unsigned)time(NULL);
This->priv->pro_type = type;
This->priv->device_type = device_type;
This->priv->port = port;
This->priv->call_cmd = call_cmd;
This->priv->master_ip = master_ip;
This->priv->room_name = room_name;
This->priv->room_id = room_id;
loadInterface(This->interface,interface);
// 创建协议状态机
video_st_machine_bz = stateMachineCreate(ST_IDLE,
stm_video_state_bz,
NELEMENTS(stm_video_state_bz),
0, videoTransSTMHanldeVideo,This,&st_debug);
video_st_machine_u9 = stateMachineCreate(ST_IDLE,
stm_video_state_u9,
NELEMENTS(stm_video_state_u9),
0, videoTransSTMHanldeVideo,This,&st_debug);
if (This->priv->pro_type == VIDEOTRANS_PROTOCOL_3000)
This->priv->st_machine = video_st_machine_bz;
else
This->priv->st_machine = video_st_machine_u9;
This->destroy = videoTransDestroy;
This->dispCallTime = videoTransDispCallTime;
This->dispCallName = videoTransDispCallName;
This->hangup = videoHangup;
This->call = videoCall;
This->cmdHandle= udpCallHandle;
This->answer = videoAnswer;
This->leaveWord = videoLeaveWord;
This->getPeerIP = videoGetPeerIP;
This->unlock = videoUnlock;
This->getIdleStatus = videoGetIdleStatus;
This->getTalkStatus = videoGetTalkStatus;
This->setStatusBusy = videosetStatusBusy;
This->setStatusIdle = videosetStatusIdle;
This->getTalkPort = videoGetTalkPort;
This->resetProtocol = videoTransResetProtocol;
This->hasUnreadLeaveWord = videoGetLeaveWord;
This->clearUnreadLeaveWord = videoClearLeaveWord;
This->enable = videoEnable;
This->callBackOverTime = videoCallbackOvertime;
This->registDev = videoRegistDev;
This->registToMaster = videoRegistToMaster;
This->getRegistDev = videoGetRegistDev;
This->getRegistOneDevIp = videoGetRegistOneDevIp;
videoTimerThreadCreate(This);
return This;
}
<file_sep>/src/gui/form_idcs.h
/*
* =============================================================================
*
* Filename: form_idcs.h
*
* Description: 各个窗口IDC汇总
*
* Version: 1.0
* Created: 2019-04-24 22:45:03
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _FORM_IDCS_H
#define _FORM_IDCS_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define IDC_FORM_MAIN_START 100
#define IDC_FORM_SETTING_START 150
#define IDC_FORM_VIDEO_START 200
#define IDC_FORM_SETTING_WIFI_STATR 250
#define IDC_FORM_PASSWORD_STATR 300
#define IDC_FORM_LOCAL_STATR 350
#define IDC_FORM_STORE_STATR 360
#define IDC_FORM_QRCODE_STATR 370
#define IDC_FORM_SET_UPDATE_STATR 380
#define IDC_FORM_MONITOR_STATR 400
#define IDC_FORM_POWEROFF_STATR 410
#define IDC_FORM_UPDATE_STATR 420
#define IDC_FORM_SETTING_DOORBELL 430
#define IDC_FORM_SETTING_RINGS 440
#define IDC_FORM_SETTING_RINGS_VOLUME 450
#define IDC_FORM_TOPMESSAGE 460
#define IDC_FORM_SETTING_PIR_STRENGTH 470
#define IDC_FORM_SETTING_PIR_TIMER 480
#define IDC_FORM_SETTING_BRIGHTNESS 490
#define IDC_FORM_SETTING_TIEMR 500
#define IDC_FORM_SETTING_DATE 510
#define IDC_FORM_SETTING_TIME 520
#define IDC_FORM_SETTING_MUTE 530
#define IDC_FORM_SETTING_SLEEPTIME 540
#define IDC_FORM_SETTING_SCREEN 550
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/gui/form_update.c
/*
* =============================================================================
*
* Filename: FormUpdate.c
*
* Description: 升级界面
*
* Version: 1.0
* Created: 2016-02-23 15:32:24
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <time.h>
#include <string.h>
#include "externfunc.h"
#include "debug.h"
#include "screen.h"
#include "config.h"
#include "my_update.h"
#include "my_video.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
extern void screenAutoCloseStop(void);
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formUpdateProc(HWND hWnd, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
int createFormUpdate(HWND hMainWnd);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
enum {
IDC_TIMER_1S = IDC_FORM_UPDATE_STATR,
IDC_CONTTENT,
IDC_POS,
};
#define WORD_DOWNLOAD "正在下载更新程序,请勿关闭电源..."
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static int auto_close = 0;
static MY_CTRLDATA ChildCtrls [] = {
STATIC_LB(0,280,1024,40,IDC_CONTTENT,WORD_DOWNLOAD,&font22,0xffffff),
STATIC_LB(0,330,1024,40,IDC_POS,"",&font22,0xffffff),
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
WS_EX_NONE ,//| WS_EX_AUTOSECONDARYDC,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "FUpdate",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formUpdateProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
};
static FormBase* form_base = NULL;
static void interfaceUiUpdateStart(void)
{
auto_close = 0;
my_video->hideVideo();
screensaverSet(1);
screenAutoCloseStop();
createFormUpdate(0);
}
static void interfaceUiUpdateStop(void)
{
// ShowWindow(form_base->hDlg,SW_HIDE);
}
static void interfaceUiUpdateFail(void)
{
SendMessage(GetDlgItem(form_base->hDlg,IDC_CONTTENT),MSG_SETTEXT,0,(LPARAM)"更新失败..");
auto_close = 1;
// ShowWindow(form_base->hDlg,SW_HIDE);
}
static void interfaceUiUpdateSuccess(void)
{
SendMessage(GetDlgItem(form_base->hDlg,IDC_CONTTENT),MSG_SETTEXT,0,(LPARAM)"更新成功,系统即将重启,请勿关闭电源...");
}
static void interfaceUiUpdateSdcard(void)
{
SendMessage(GetDlgItem(form_base->hDlg,IDC_CONTTENT),MSG_SETTEXT,0,(LPARAM)"即将进行SD卡升级,请勿关闭电源...");
}
static void interfaceUiUpdateDowloadSuccess(void)
{
SendMessage(GetDlgItem(form_base->hDlg,IDC_CONTTENT),MSG_SETTEXT,0,(LPARAM)"下载完成,正在检测升级包...");
}
static void interfaceUiUpdatePos(int pos)
{
char buf[16] = {0};
sprintf(buf,"%d%%",pos);
SendMessage(GetDlgItem(form_base->hDlg,IDC_POS),MSG_SETTEXT,0,(LPARAM)buf);
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
if (my_update) {
my_update->interface->uiUpdateStart = interfaceUiUpdateStart;
my_update->interface->uiUpdateSuccess = interfaceUiUpdateSuccess;
my_update->interface->uiUpdateSdCard = interfaceUiUpdateSdcard;
my_update->interface->uiUpdateDownloadSuccess = interfaceUiUpdateDowloadSuccess;
my_update->interface->uiUpdateFail = interfaceUiUpdateFail;
my_update->interface->uiUpdatePos = interfaceUiUpdatePos;
my_update->interface->uiUpdateStop = interfaceUiUpdateStop;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formUpdateProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ---------------------------------------------------------------------------*/
static int formUpdateProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case MSG_TIMER:
{
if (wParam == IDC_TIMER_1S && auto_close == 0) {
return 0;
}
} break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormUpdate(HWND hMainWnd)
{
HWND Form = Screen.Find(form_base_priv.name);
if(Form) {
ShowWindow(Form,SW_SHOWNORMAL);
SendMessage(GetDlgItem(form_base->hDlg,IDC_POS),MSG_SETTEXT,0,(LPARAM)"");
SendMessage(GetDlgItem(form_base->hDlg,IDC_CONTTENT),MSG_SETTEXT,0,(LPARAM)WORD_DOWNLOAD);
Screen.setCurrent(form_base_priv.name);
} else {
ShowWindow(Form,SW_SHOWNORMAL);
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
<file_sep>/src/gui/form_setting_update.c
/*
* =============================================================================
*
* Filename: form_setting_Update.c
*
* Description: Update设置界面
*
* Version: 1.0
* Created: 2018-03-01 23:32:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <string.h>
#include "externfunc.h"
#include "screen.h"
#include "my_button.h"
#include "my_title.h"
#include "config.h"
#include "protocol.h"
#include "my_update.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formSettingUpdateProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void buttonNotify(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonUpdateLocal(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonUpdateNetwork(HWND hwnd, int id, int nc, DWORD add_data);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_SET_LOCAL > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define BMP_LOCAL_PATH "setting/"
enum {
IDC_TIMER_1S = IDC_FORM_SET_UPDATE_STATR,
IDC_STATIC_TEXT_FIND,
IDC_STATIC_TEXT_VERSION,
IDC_STATIC_TEXT_CONTTENT,
IDC_STATIC_TEXT_NOTFIND,
IDC_STATIC_IMAGE_UPDATE,
IDC_STATIC_IMAGE_WARNING,
IDC_BUTTON_UPDATE_LOCAL,
IDC_BUTTON_UPDATE_NETWORK,
IDC_TITLE,
};
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static BITMAP bmp_warning; // 警告
static BITMAP bmp_update; // 升级
static int bmp_load_finished = 0;
static int flag_timer_stop = 0;
static BmpLocation bmp_load[] = {
{&bmp_warning, BMP_LOCAL_PATH"ico_警告.png"},
{&bmp_update, BMP_LOCAL_PATH"image.png"},
{NULL},
};
static MY_CTRLDATA ChildCtrls [] = {
STATIC_IMAGE(103,75l,796,272,IDC_STATIC_IMAGE_UPDATE,(DWORD)&bmp_update),
STATIC_IMAGE(452,216,120,120,IDC_STATIC_IMAGE_WARNING,(DWORD)&bmp_warning),
STATIC_LB_LEFT(292,197,220,50,IDC_STATIC_TEXT_FIND,"发现新版本",&font36,0xffffff),
STATIC_LB_LEFT(292,247,220,50,IDC_STATIC_TEXT_VERSION,"",&font36,0xffffff),
STATIC_LB_LEFT(361,378,400,150,IDC_STATIC_TEXT_CONTTENT,"",&font20,0xffffff),
STATIC_LB_LEFT(467,358,100,30,IDC_STATIC_TEXT_NOTFIND,"暂无新版本",&font20,0xffffff),
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
// WS_EX_AUTOSECONDARYDC,
WS_EX_NONE,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "FsetUpdate",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formSettingUpdateProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
.auto_close_time_set = 30,
};
static MyCtrlTitle ctrls_title[] = {
{
IDC_TITLE,
MYTITLE_LEFT_EXIT,
MYTITLE_RIGHT_NULL,
0,0,1024,40,
"软件/固件/单片机版本",
"",
0xffffff, 0x333333FF,
buttonNotify,
},
{0},
};
static MyCtrlButton ctrls_button[] = {
{
.idc = IDC_BUTTON_UPDATE_LOCAL,
.flag = MYBUTTON_TYPE_TWO_STATE|MYBUTTON_TYPE_PRESS_COLOR|MYBUTTON_TYPE_TEXT_CENTER,
.img_name = "本地升级",
.x = 0, .y = 540, .w = 511, .h = 60,
.notif_proc = buttonUpdateLocal},
{
.idc = IDC_BUTTON_UPDATE_NETWORK,
.flag = MYBUTTON_TYPE_TWO_STATE|MYBUTTON_TYPE_PRESS_COLOR|MYBUTTON_TYPE_TEXT_CENTER,
.img_name ="网络升级",
.x = 512,.y = 540,.w = 512, .h = 60,
.notif_proc = buttonUpdateNetwork},
{0},
};
static FormBase* form_base = NULL;
static void enableAutoClose(void)
{
Screen.setCurrent(form_base_priv.name);
flag_timer_stop = 0;
}
/* ----------------------------------------------------------------*/
/**
* @brief buttonNotify 退出按钮
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ----------------------------------------------------------------*/
static void buttonNotify(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc == MYTITLE_BUTTON_EXIT)
ShowWindow(GetParent(hwnd),SW_HIDE);
}
static void buttonUpdateLocal(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
if (protocol->isNeedToUpdate(NULL,NULL) == UPDATE_TYPE_SDCARD) {
flag_timer_stop = 1;
myUpdateStart(UPDATE_TYPE_SDCARD,NULL,0,NULL);
}
}
static void buttonUpdateNetwork(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
if (protocol->isNeedToUpdate(NULL,NULL) == UPDATE_TYPE_SERVER) {
flag_timer_stop = 1;
myUpdateStart(UPDATE_TYPE_SERVER,NULL,0,NULL);
}
}
void formSettingUpdateLoadBmp(void)
{
if (bmp_load_finished == 1)
return;
printf("[%s]\n", __FUNCTION__);
bmpsLoad(bmp_load);
bmp_load_finished = 1;
}
static void updateInfo(HWND hDlg)
{
char version[16] = {0},content[256] = {0};
if (protocol->isNeedToUpdate(version,content)) {
ShowWindow(GetDlgItem(hDlg,IDC_STATIC_IMAGE_WARNING),SW_HIDE);
ShowWindow(GetDlgItem(hDlg,IDC_STATIC_TEXT_NOTFIND),SW_HIDE);
ShowWindow(GetDlgItem(hDlg,IDC_STATIC_IMAGE_UPDATE),SW_SHOWNORMAL);
ShowWindow(GetDlgItem(hDlg,IDC_STATIC_TEXT_FIND),SW_SHOWNORMAL);
ShowWindow(GetDlgItem(hDlg,IDC_STATIC_TEXT_VERSION),SW_SHOWNORMAL);
ShowWindow(GetDlgItem(hDlg,IDC_STATIC_TEXT_CONTTENT),SW_SHOWNORMAL);
SendMessage(GetDlgItem(hDlg,IDC_STATIC_TEXT_VERSION),
MSG_SETTEXT,0,(LPARAM)version);
SendMessage(GetDlgItem(hDlg,IDC_STATIC_TEXT_CONTTENT),
MSG_SETTEXT,0,(LPARAM)content);
} else {
ShowWindow(GetDlgItem(hDlg,IDC_STATIC_IMAGE_WARNING),SW_SHOWNORMAL);
ShowWindow(GetDlgItem(hDlg,IDC_STATIC_TEXT_NOTFIND),SW_SHOWNORMAL);
ShowWindow(GetDlgItem(hDlg,IDC_STATIC_IMAGE_UPDATE),SW_HIDE);
ShowWindow(GetDlgItem(hDlg,IDC_STATIC_TEXT_FIND),SW_HIDE);
ShowWindow(GetDlgItem(hDlg,IDC_STATIC_TEXT_VERSION),SW_HIDE);
ShowWindow(GetDlgItem(hDlg,IDC_STATIC_TEXT_CONTTENT),SW_HIDE);
}
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_title[i].idc != 0; i++) {
ctrls_title[i].font = font20;
createMyTitle(hDlg,&ctrls_title[i]);
}
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
createMyButton(hDlg,&ctrls_button[i]);
}
updateInfo(hDlg);
}
/* ----------------------------------------------------------------*/
/**
* @brief formSettingUpdateProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ----------------------------------------------------------------*/
static int formSettingUpdateProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
switch(message) // 自定义消息
{
case MSG_TIMER:
{
if (flag_timer_stop)
return 0;
} break;
case MSG_ENABLE_WINDOW:
enableAutoClose();
break;
case MSG_DISABLE_WINDOW:
flag_timer_stop = 1;
break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormSettingUpdate(HWND hMainWnd,void (*callback)(void))
{
HWND Form = Screen.Find(form_base_priv.name);
if(Form) {
Screen.setCurrent(form_base_priv.name);
updateInfo(form_base->hDlg);
ShowWindow(Form,SW_SHOWNORMAL);
} else {
if (bmp_load_finished == 0) {
return 0;
}
form_base_priv.callBack = callback;
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
<file_sep>/src/app/protocol_talk.c
/*
* =============================================================================
*
* Filename: protocol_talk.c
*
* Description: 对讲协议
*
* Version: 1.0
* Created: 2019-06-05 10:29:06
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "sql_handle.h"
#include "cJSON.h"
#include "json_dec.h"
#include "protocol.h"
#include "my_video.h"
#include "my_mixer.h"
#include "my_audio.h"
#include "my_echo.h"
#include "ucpaas/ucpaas.h"
#include "udp_server.h"
#include "config.h"
#include "udp_talk/udp_talk_protocol.h"
#include "udp_talk/udp_talk_transport.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
enum {
MSG_TYPE_CALL = 1, // 呼叫
MSG_TYPE_UNLOCK, // 开锁
MSG_TYPE_SLEEP, // 睡眠
MSG_TYPE_MIC_CLOSE, // 禁麦
MSG_TYPE_MIC_OPEN, // 开麦
MSG_TYPE_CAPTURE, // 抓拍
MSG_TYPE_RECORD_START, // 开始录视频
MSG_TYPE_RECORD_STOP, // 停止录视频
MSG_TYPE_ELECTRIC, // 电量
MSG_TYPE_NEED_CALL_APP, // 挂机需要转呼APP
MSG_TYPE_RESET_TALK_TIME, // 重置剩余通话时间(只针对苹果手机)
};
enum {
DEV_TYPE_APP = 0,
DEV_TYPE_CATEYE,
DEV_TYPE_OUTDOOR,
};
/* 透传协议示例,messageType为以上枚举类型
{
"messageType":9,
"deviceType":1,
"deviceNumber":"机身码",
"fromId":"对讲Id",
"messageContent":"",
"data":{
"electricQuantity":60, // 剩余百分60的电量
"time":"2019-06-21 13:13"
}
}
*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
ProtocolTalk *protocol_talk;
static UserStruct local_user;
static UserStruct peer_user;
static int has_connect = 0; // 判断是否有连接过,如果有,则重连调用disconnect
static int audio_fp = -1;
static int mic_open = 0; // mic状态 0关闭 1开启
static void (*dialCallBack)(int result);
static void reloadLocalTalk(void)
{
memset(&local_user,0,sizeof(UserStruct));
sqlGetUserInfoUseType(USER_TYPE_CATEYE,local_user.id,local_user.token,local_user.nick_name,&local_user.scope);
printf("[%s]id:%s,token:%s\n",__func__,local_user.id,local_user.token );
}
static void dial(char *user_id,void (*callBack)(int result))
{
if (protocol_video && protocol_talk->type == PROTOCOL_TALK_LAN) {
protocol_video->call(protocol_video,user_id);
} else {
if (protocol_video)
protocol_video->setStatusBusy(protocol_video);
#ifdef USE_UCPAAS
ucsDial(user_id);
memset(&peer_user,0,sizeof(UserStruct));
strcpy(peer_user.id,user_id);
dialCallBack = callBack;
#endif
}
}
static void hangup(int need_transfer)
{
printf("need:%d\n",need_transfer );
if (protocol_talk->type == PROTOCOL_TALK_LAN) {
myAudioStopPlay();
if (protocol_video)
protocol_video->hangup(protocol_video);
if (udp_talk_trans)
udp_talk_trans->close(udp_talk_trans);
} else {
#ifdef USE_UCPAAS
ucsHangup();
if (need_transfer) {
char send_buff[256];
sprintf(send_buff,"{\\\"messageType\\\":%d,\\\"deviceType\\\":%d,\\\"deviceNumber\\\":\\\"%s\\\",\\\"fromId\\\":\\\"%s\\\",\\\"messageContent\\\":\\\"\\\"}",
MSG_TYPE_NEED_CALL_APP,DEV_TYPE_CATEYE,g_config.imei,local_user.id);
ucsSendCmd(send_buff,peer_user.id);
}
if (protocol_video)
protocol_video->setStatusIdle(protocol_video);
#endif
}
}
static void unlock(void)
{
if (protocol_video && protocol_talk->type == PROTOCOL_TALK_LAN) {
protocol_video->unlock(protocol_video);
} else {
#ifdef USE_UCPAAS
char send_buff[256];
sprintf(send_buff,"{\\\"messageType\\\":%d,\\\"deviceType\\\":%d,\\\"deviceNumber\\\":\\\"%s\\\",\\\"fromId\\\":\\\"%s\\\",\\\"messageContent\\\":\\\"\\\"}",
MSG_TYPE_UNLOCK,DEV_TYPE_CATEYE,g_config.imei,local_user.id);
ucsSendCmd(send_buff,peer_user.id);
printf("send:%s,id:%s\n",send_buff,peer_user.id );
#endif
}
}
static void answer(void)
{
myAudioStopPlay();
if (protocol_talk->type == PROTOCOL_TALK_LAN) {
if (protocol_video)
protocol_video->answer(protocol_video);
if (udp_talk_trans)
udp_talk_trans->startAudio(udp_talk_trans);
} else {
#ifdef USE_UCPAAS
ucsAnswer();
#endif
}
}
static void talkConnect(void)
{
#ifdef USE_UCPAAS
if (ucsConnect(local_user.token))
has_connect = 1;
#endif
}
static void talkReconnect(void)
{
#ifdef USE_UCPAAS
if (has_connect)
ucsDisconnect();
ucsConnect(local_user.token);
#endif
}
static void sendVideo(void *data,int size)
{
#ifdef USE_UCPAAS
ucsSendVideo(data,size);
#endif
}
static void receiveVideo(void *data,int *size)
{
if (udp_talk_trans && protocol_talk->type == PROTOCOL_TALK_LAN) {
*size = udp_talk_trans->getVideo(udp_talk_trans,data);
} else {
#ifdef USE_UCPAAS
long long timeStamp = 0;
int frameType = 0;
ucsReceiveVideo(data, size, &timeStamp, &frameType);
#endif
}
}
static void cbDialFail(void *arg)
{
if (protocol_talk->type == PROTOCOL_TALK_LAN)
return;
if (dialCallBack)
dialCallBack(0);
}
static void cbAnswer(void *arg)
{
if (protocol_talk->type == PROTOCOL_TALK_LAN)
return;
if (my_video)
my_video->videoAnswer(CALL_DIR_OUT,DEV_TYPE_ENTRANCEMACHINE);
}
static void cbHangup(void *arg)
{
int type = *(int *)arg;
if (protocol_talk->type == PROTOCOL_TALK_LAN
|| type == 0)
return;
printf("[%s,%d]type:%d\n", __func__,__LINE__,type);
if (my_video) {
if (type == 2)
my_video->videoHangup(HANGUP_TYPE_PEER);
else if (type == 1)
my_video->videoHangup(HANGUP_TYPE_BUTTON);
}
if (my_mixer) {
if (audio_fp > 0)
my_mixer->DeInitPlay(my_mixer,&audio_fp);
}
dialCallBack = NULL;
myAudioStopPlay();
}
static void cbDialRet(void *arg)
{
if (dialCallBack)
dialCallBack(1);
}
static void cblIncomingCall(void *arg)
{
if (protocol_video && protocol_video->getIdleStatus(protocol_video) == 0) {
#ifdef USE_UCPAAS
// ucsHangup();
#endif
return;
}
printf("[%s]%d\n", __func__,protocol_video->getIdleStatus(protocol_video));
protocol_talk->type = PROTOCOL_TALK_CLOUD;
if (protocol_video)
protocol_video->setStatusBusy(protocol_video);
if (my_video)
my_video->videoCallIn((char *)arg);
strcpy(peer_user.id,(char *)arg);
}
static void cbSendCmd(void *arg)
{
}
static void cbReceivedCmd(const char *user_id,void *arg)
{
if (protocol_talk->type == PROTOCOL_TALK_LAN)
return;
printf("%s\n", (char *)arg);
char *data = (char *)arg;
char *j_data = (char *)calloc(1,strlen(data));
char *p = j_data;
while (*data != '\0') {
if (*data != '\\') {
*p = *data;
p++;
}
data++;
}
CjsonDec *dec = cjsonDecCreate(j_data);
if (!dec) {
printf("json dec create fail!\n");
if (j_data)
free(j_data);
return ;
}
dec->print(dec);
int message_type = dec->getValueInt(dec, "messageType");
switch (message_type)
{
case MSG_TYPE_UNLOCK :
break;
case MSG_TYPE_MIC_OPEN :
mic_open = 1;
break;
case MSG_TYPE_MIC_CLOSE :
mic_open = 0;
break;
case MSG_TYPE_CAPTURE :
my_video->capture(CAP_TYPE_TALK,1,NULL,NULL);
break;
case MSG_TYPE_RECORD_START:
my_video->recordStart(CAP_TYPE_TALK);
break;
case MSG_TYPE_RECORD_STOP:
my_video->recordStop();
break;
case MSG_TYPE_RESET_TALK_TIME:
{
if(dec->changeCurrentObj(dec,"data")) {
printf("change talk_time fail\n");
break;
}
int talk_time = dec->getValueInt(dec, "talk_time");
my_video->resetCallTime(talk_time);
}
break;
default:
break;
}
if (j_data)
free(j_data);
if (dec)
dec->destroy(dec);
}
static void cbInitAudio(unsigned int rate,unsigned int bytes_per_sample,unsigned int channle)
{
if (protocol_talk->type == PROTOCOL_TALK_LAN)
return;
mic_open = 1;
if (my_mixer)
my_mixer->InitPlayAndRec(my_mixer,&audio_fp,rate,channle);
}
static void cbStartRecord(unsigned int rate,unsigned int bytes_per_sample,unsigned int channle)
{
}
static void cbRecording(char *data,unsigned int size)
{
if (protocol_talk->type == PROTOCOL_TALK_LAN)
return;
char audio_buff[1024] = {0};
if (my_mixer ) {
int real_size = my_mixer->Read(my_mixer,audio_buff,size,2);
if (mic_open) {
memcpy(data,audio_buff,real_size);
}
if (my_video)
my_video->recordWriteCallback(audio_buff,real_size);
}
}
static void cbPlayAudio(const char *data,unsigned int size)
{
if (protocol_talk->type == PROTOCOL_TALK_LAN)
return;
if (my_mixer) {
my_mixer->Write(my_mixer,audio_fp,data,size);
}
}
static Callbacks interface = {
.dialFail = cbDialFail,
.answer = cbAnswer,
.hangup = cbHangup,
.dialRet = cbDialRet,
.incomingCall = cblIncomingCall,
.sendCmd = cbSendCmd,
.receivedCmd = cbReceivedCmd,
.initAudio = cbInitAudio,
.startRecord = cbStartRecord,
.recording = cbRecording,
.playAudio = cbPlayAudio,
};
static void videoCallbackOvertime(int ret,void *CallBackData)
{
if(ret != MSG_SENDTIMEOUT) {
return ;
}
VideoTrans * This = (VideoTrans *)CallBackData;
This->callBackOverTime(This);
}
static void videoUdpSend(VideoTrans *This,
char *ip,int port,void *data,int size,int enable_call_back)
{
if (enable_call_back)
udp_server->AddTask(udp_server,
ip,port,data,
size,3,videoCallbackOvertime,This);
else
udp_server->AddTask(udp_server,
ip,port,data,
size,3,NULL,NULL);
}
static void videoSendMessageStatus(VideoTrans *This,VideoUiStatus status)
{
switch(status)
{
case VIDEOTRANS_UI_NONE: // 不做处理
break;
case VIDEOTRANS_UI_SHAKEHANDS: // 3000握手命令
protocol_talk->type = PROTOCOL_TALK_LAN;
break;
case VIDEOTRANS_UI_CALLIP: // 呼出
break;
case VIDEOTRANS_UI_RING: // 呼入响铃
{
protocol_talk->type = PROTOCOL_TALK_LAN;
if (my_video)
my_video->videoCallIn("门口机");
if (udp_talk_trans) {
udp_talk_trans->init(udp_talk_trans,This->getPeerIP(This),8800);
udp_talk_trans->buildConnect(udp_talk_trans);
}
myAudioPlayRing();
}
break;
case VIDEOTRANS_UI_LEAVE_WORD: // 留言
break;
case VIDEOTRANS_UI_RETCALL: // 呼出到管理中心,室内机收到回应
case VIDEOTRANS_UI_RETCALL_MONITOR: // 呼出到门口机,户门口机收到回应,显示开锁按钮
if (udp_talk_trans) {
udp_talk_trans->init(udp_talk_trans,This->getPeerIP(This),8800);
udp_talk_trans->buildConnect(udp_talk_trans);
}
break;
case VIDEOTRANS_UI_FAILCOMM: // 通信异常
break;
case VIDEOTRANS_UI_FAILSHAKEHANDS: // 握手异常
break;
case VIDEOTRANS_UI_FAILBUSY: // 对方忙
break;
case VIDEOTRANS_UI_FAILABORT: // 突然中断
break;
case VIDEOTRANS_UI_ANSWER: // 本机接听
break;
case VIDEOTRANS_UI_ANSWER_EX: // 分机接听
break;
case VIDEOTRANS_UI_OVER: // 挂机
printf("[%s,%d]\n", __func__,__LINE__);
if (my_video)
my_video->videoHangup(1);
break;
default:
break;
}
}
static VideoInterface video_interface = {
.udpSend = videoUdpSend,
.sendMessageStatus = videoSendMessageStatus,
};
static int udpSendAudio(Rtp *This,void *data,int size)
{
if (my_mixer)
return my_mixer->Read(my_mixer,data,size,1 );
else
return 0;
}
static void udpReceiveAudio(Rtp *This,void *data,int size)
{
if (my_mixer)
my_mixer->Write(my_mixer,audio_fp,data,size);
}
static void udpStart(Rtp *This)
{
printf("[%s]\n", __func__);
if (my_mixer) {
my_mixer->SetVolumeEx(my_mixer,g_config.talk_volume);
my_mixer->InitPlayAndRec(my_mixer,&audio_fp,8000,1);
}
}
static void udpReceiveEnd(Rtp *This)
{
printf("[%s]\n", __func__);
if (my_mixer) {
if (audio_fp > 0)
my_mixer->DeInitPlay(my_mixer,&audio_fp);
}
}
static void udpCmd(char *ip,int port, char *data,int size)
{
if (protocol_video)
protocol_video->cmdHandle(protocol_video,ip,port,data,size);
}
static UdpTalkTransInterface rtp_interface = {
.receiveAudio = udpReceiveAudio,
.receiveEnd = udpReceiveEnd,
.sendAudio = udpSendAudio,
.start = udpStart,
};
void registTalk(void)
{
protocol_talk = (ProtocolTalk *) calloc(1,sizeof(ProtocolTalk));
protocol_talk->dial = dial;
protocol_talk->answer = answer;
protocol_talk->hangup = hangup;
protocol_talk->connect = talkConnect;
protocol_talk->reconnect = talkReconnect;
protocol_talk->reload = reloadLocalTalk;
protocol_talk->sendVideo = sendVideo;
protocol_talk->receiveVideo = receiveVideo;
protocol_talk->unlock = unlock;
protocol_talk->type = PROTOCOL_TALK_CLOUD;
#ifdef USE_UCPAAS
registUcpaas(&interface);
protocol_talk->reload();
protocol_talk->connect();
#endif
protocol_talk->udpCmd = udpCmd;
protocol_video = videoTransCreate(&video_interface,
7800,0,3,VIDEOTRANS_PROTOCOL_3000,"","123","0101");
protocol_video->enable(protocol_video);
udp_talk_trans = createRtp(&rtp_interface,protocol_video);
rkEchoInit();
}
<file_sep>/src/wireless/my_mqtt.c
/*
* =============================================================================
*
* Filename: my_mqtt.c
*
* Description: 封装mqtt接口
*
* Version: 1.0
* Created: 2019-05-21 11:33:50
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTAsync.h"
#include "my_mqtt.h"
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
// #define DBG_MQTT
#ifdef DBG_MQTT
#define DBG_P( ... ) \
do { \
printf("[MQTT DEBUG]"); \
printf( __VA_ARGS__ ); \
}while(0)
#else
#define DBG_P( ... )
#endif
#define TRUE 1
#define FALSE 0
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
MyMqtt *my_mqtt = NULL;
static MQTTAsync client;
static MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
static int (*mqttConnectCallBack)(void* context, char* topicName, int topicLen, void* payload);
static void (*mqttConnectSuccess)(void* context);
static void (*mqttConnectFailure)(void* context);
static void (*mqttSubcribeSuccess)(void* context);
static void (*mqttSubcribeFailure)(void* context);
static void connectionLost(void* context, char* cause)
{
int rc = 0;
DBG_P("%s()\n",__func__);
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
DBG_P("connectionLost Failed to start connect, return code %d\n", rc);
return;
}
static int messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* message)
{
DBG_P("%s()\n",__func__);
if (mqttConnectCallBack)
mqttConnectCallBack(context,topicName,topicLen,message->payload);
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
return TRUE;
}
static void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
DBG_P("%s()\n",__func__);
if (mqttConnectFailure)
mqttConnectFailure(context);
}
static void onConnect(void* context, MQTTAsync_successData* response)
{
DBG_P("%s()\n",__func__);
if (mqttConnectSuccess)
mqttConnectSuccess(context);
}
static void onSubscribeSuccess(void* context,MQTTAsync_successData* response)
{
DBG_P("%s()\n",__func__);
if (mqttSubcribeSuccess)
mqttSubcribeSuccess(context);
}
static void onSubscribeFailure(void* context, MQTTAsync_failureData* response)
{
DBG_P("%s()\n",__func__);
if (mqttSubcribeFailure)
mqttSubcribeFailure(context);
}
static int send(char *pub_topic,int len,void *payload)
{
printf("mqtt send:%s\n", (char *)payload);
if (MQTTAsync_send(client, pub_topic, len, payload, 2, 0, NULL) == MQTTASYNC_SUCCESS)
return TRUE;
else
return FALSE;
}
static int subcribe(char* topic,
void (*onSuccess)(void * context),
void (*onFailure)(void *context) )
{
int rc;
MQTTAsync_responseOptions ropts = MQTTAsync_responseOptions_initializer;
mqttSubcribeSuccess = onSuccess;
mqttSubcribeFailure = onFailure;
ropts.onSuccess = onSubscribeSuccess;
ropts.onFailure = onSubscribeFailure;
ropts.context = client;
if ((rc = MQTTAsync_subscribe(client, topic, 2, &ropts)) != MQTTASYNC_SUCCESS) {
DBG_P("Failed to start subscribe:%s, return code %d\n", topic, rc);
return FALSE;
}
return TRUE;
}
static int connect(char *url,char *client_id, int keepalive_interval,char *username,char *password,
int (*callBack)(void* context, char* topicName, int topicLen, void* payload),
void (*onSuccess)(void * context),
void (*onFailure)(void *context) )
{
int rc = MQTTAsync_create(&client, url, client_id, MQTTCLIENT_PERSISTENCE_NONE, NULL);
if (rc != MQTTASYNC_SUCCESS) {
MQTTAsync_destroy(&client);
return FALSE;
}
mqttConnectCallBack = callBack;
mqttConnectSuccess = onSuccess;
mqttConnectFailure = onFailure;
MQTTAsync_setCallbacks(client, client, connectionLost, messageArrived, NULL);
conn_opts.keepAliveInterval = keepalive_interval;
conn_opts.cleansession = 0;
conn_opts.username = username;
conn_opts.password = <PASSWORD>;
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
conn_opts.context = client;
conn_opts.automaticReconnect = 1;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS) {
DBG_P("myconnect Failed to start connect, return code %d\n", rc);
return FALSE;
}
return TRUE;
}
MyMqtt * myMqttCreate(void)
{
// 只创建一次接口
if (my_mqtt)
return my_mqtt;
my_mqtt = (MyMqtt *) calloc(1,sizeof(MyMqtt));
my_mqtt->subcribe = subcribe;
my_mqtt->connect = connect;
my_mqtt->send = send;
return my_mqtt;
}
<file_sep>/src/gui/form_setting_wifi.c
/*
* =============================================================================
*
* Filename: form_setting_wifi.c
*
* Description: wifi设置界面
*
* Version: 1.0
* Created: 2018-03-01 23:32:41
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <string.h>
#include "screen.h"
#include "iwlib.h"
#include "my_button.h"
#include "my_title.h"
#include "config.h"
#include "externfunc.h"
#include "thread_helper.h"
#include "form_base.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
extern int createFormPassword(HWND hMainWnd,char *account,
void (*callback)(void),
void (*getPassword)(char *account,char *password));
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
static int formSettingWifiProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam);
static void wifiLoadData(void *ap_info,int ap_cnt);
static void buttonTitleNotify(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonConnect(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonRefresh(HWND hwnd, int id, int nc, DWORD add_data);
static void buttonAdd(HWND hwnd, int id, int nc, DWORD add_data);
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#if DBG_FORM_SET_LOCAL > 0
#define DBG_P( x... ) printf( x )
#else
#define DBG_P( x... )
#endif
#define BMP_LOCAL_PATH "setting/"
enum {
IDC_TIMER_1S = IDC_FORM_SETTING_WIFI_STATR,
IDC_STATIC_IMG_WARNING,
IDC_STATIC_TEXT_WARNING,
IDC_SCROLLVIEW,
IDC_BUTTON_TITLE,
IDC_BUTTON_ADD,
IDC_BUTTON_REFRESH,
IDC_TITLE,
};
enum {
SCROLLVIEW_ITEM_TYPE_TITLE,
SCROLLVIEW_ITEM_TYPE_LIST,
};
struct ScrollviewItem {
int enable; // 是否选中
int security; // 加密 0,1
int strength; // 信号强度
char text[32]; // 文字
int index; // 元素位置
};
// 控件滑动相关操作
struct ScrollviewOperation{
RECT rc ; // 控件空间坐标
int cur_pos ; // 控件当前y坐标
int old_pos ; // 控件移动时上一次坐标
int state; // 按下状态
int step; // 移动步长
int timer_cur_pos; // 定时器读取当前y坐标
int timer_old_pos; // 定时器读取上一次y坐标
int notified; // 是否有触发回调,有滑动触发时,不回调
int moved; // 是否有滑动触发
int total_item; // 当前总条数
};
#define FILL_BMP_STRUCT(left,top,img) \
FillBoxWithBitmap(hdc,left, top,img.bmWidth,img.bmHeight,&img)
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static HWND hScrollView;
static struct ScrollviewOperation scro_opt;
static int bmp_load_finished = 0;
static int flag_timer_stop = 0;
static int connect_wifi_interval = 0; // 链接wifi间隔时间
static int refresh_wifi_interval = 0; // 刷新列表wifi间隔时间
static BITMAP bmp_warning; // 警告
static BITMAP bmp_security; // 加密
static BITMAP bmp_select; // 选中
static BITMAP bmp_enter; // 进入
static BITMAP bmp_wifi[3]; // wifi强度
static struct ScrollviewItem wifi_list_title;
static struct ScrollviewItem wifi_list[100];
static TcWifiScan ap_info[100];
static TcWifiScan select_ap;
static int thread_move_start = 0;
static BmpLocation bmp_load[] = {
{&bmp_warning, BMP_LOCAL_PATH"ico_警告.png"},
{&bmp_security, BMP_LOCAL_PATH"ico_lock.png"},
{&bmp_select, BMP_LOCAL_PATH"ico_对.png"},
{&bmp_enter, BMP_LOCAL_PATH"ico_返回_1.png"},
{&bmp_wifi[0], BMP_LOCAL_PATH"ico_wifi_2.png"},
{&bmp_wifi[1], BMP_LOCAL_PATH"ico_wifi_1.png"},
{&bmp_wifi[2], BMP_LOCAL_PATH"ico_wifi.png"},
{NULL},
};
static MY_CTRLDATA ChildCtrls [] = {
STATIC_IMAGE(452,216,120,120,IDC_STATIC_IMG_WARNING,(DWORD)&bmp_warning),
STATIC_LB(0,358,1024,25,IDC_STATIC_TEXT_WARNING,"WIFI已关闭",&font20,0xffffff),
SCROLLVIEW(0,150,1024,390,IDC_SCROLLVIEW),
};
static MY_DLGTEMPLATE DlgInitParam =
{
WS_NONE,
WS_EX_NONE ,//| WS_EX_AUTOSECONDARYDC,
0,0,SCR_WIDTH,SCR_HEIGHT,
"",
0, 0, //menu and icon is null
sizeof(ChildCtrls)/sizeof(MY_CTRLDATA),
ChildCtrls, //pointer to control array
0 //additional data,must be zero
};
static FormBasePriv form_base_priv= {
.name = "Fsetwifi",
.idc_timer = IDC_TIMER_1S,
.dlgProc = formSettingWifiProc,
.dlgInitParam = &DlgInitParam,
.initPara = initPara,
.auto_close_time_set = 10,
};
static MyCtrlTitle ctrls_title[] = {
{
IDC_TITLE,
MYTITLE_LEFT_EXIT,
MYTITLE_RIGHT_SWICH,
0,0,1024,40,
"WIFI设置",
"",
0xffffff, 0x333333FF,
buttonTitleNotify,
},
{0},
};
static MyCtrlButton ctrls_button[] = {
{
.idc = IDC_BUTTON_TITLE,
.flag = MYBUTTON_TYPE_TWO_STATE|MYBUTTON_TYPE_PRESS_TRANSLATE|MYBUTTON_TYPE_TEXT_CENTER,
.img_name = "",
.x = 0,.y = 40,.w = 1024, .h = 60,
.notif_proc = buttonConnect
},
{
.idc = IDC_BUTTON_ADD,
.flag = MYBUTTON_TYPE_TWO_STATE|MYBUTTON_TYPE_PRESS_COLOR|MYBUTTON_TYPE_TEXT_CENTER,
.img_name = "刷新",
.x = 0, .y = 540, .w = 511, .h = 60,
.notif_proc = buttonRefresh
},
{
.idc = IDC_BUTTON_REFRESH,
.flag = MYBUTTON_TYPE_TWO_STATE|MYBUTTON_TYPE_PRESS_COLOR|MYBUTTON_TYPE_TEXT_CENTER,
.img_name = "添加",
.x = 512,.y = 540,.w = 512, .h = 60,
.notif_proc = buttonAdd
},
{0},
};
static FormBase* form_base = NULL;
static void enableAutoClose(void)
{
Screen.setCurrent(form_base_priv.name);
flag_timer_stop = 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief updateConnectWifi 更新当前连接wifi状态
*/
/* ---------------------------------------------------------------------------*/
static void updateConnectWifi(void)
{
strcpy(wifi_list_title.text,g_config.net_config.ssid);
RECT rc;
rc.left = 0;
rc.top = 40;
rc.right = 1024;
rc.bottom = 200;
InvalidateRect (form_base->hDlg, &rc, TRUE);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief saveConfigConnectCallback 设置完密码,返回后连接wifi
*/
/* ---------------------------------------------------------------------------*/
static void saveConfigConnectCallback(void)
{
int net_level = 0;
if (getWifiConfig(&net_level) != 0)
wifi_list_title.enable = 0;
else
wifi_list_title.enable = net_level;
updateConnectWifi();
wifiConnect();
}
/* ---------------------------------------------------------------------------*/
/**
* @brief getPassword 密码设置确定后回调函数
*
* @param account 账号
* @param password <PASSWORD>
*/
/* ---------------------------------------------------------------------------*/
static void getPassword(char *account,char *password)
{
if (account) {
strcpy(g_config.net_config.ssid,account);
} else {
strcpy(g_config.net_config.ssid,select_ap.ssid);
}
strcpy(g_config.net_config.password,<PASSWORD>);
strcpy(g_config.net_config.security,"WPA/WPA2 PSK");
ConfigSavePublicCallback(saveConfigConnectCallback);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief showSwichOnOff 切换是否连接wifi
*
* @param hwnd
* @param on_off
*/
/* ---------------------------------------------------------------------------*/
static void showSwichOnOff(HWND hwnd,int on_off)
{
if (on_off) {
ShowWindow(GetDlgItem(hwnd,IDC_STATIC_IMG_WARNING),SW_HIDE);
ShowWindow(GetDlgItem(hwnd,IDC_STATIC_TEXT_WARNING),SW_HIDE);
ShowWindow(GetDlgItem(hwnd,IDC_SCROLLVIEW),SW_SHOWNORMAL);
ShowWindow(GetDlgItem(hwnd,IDC_BUTTON_TITLE),SW_SHOWNORMAL);
strcpy(wifi_list_title.text,g_config.net_config.ssid);
wifiConnectStart();
updateConnectWifi();
#ifndef X86
getWifiList(ap_info,wifiLoadData);
#else
int i;
for (i=0; i<10; i++) {
sprintf(ap_info[i].ssid,"TEST-->%d",i);
ap_info[i].encry = AWSS_ENC_TYPE_AES;
}
wifiLoadData(ap_info,10);
#endif
} else {
ShowWindow(GetDlgItem(hwnd,IDC_STATIC_IMG_WARNING),SW_SHOWNORMAL);
ShowWindow(GetDlgItem(hwnd,IDC_STATIC_TEXT_WARNING),SW_SHOWNORMAL);
ShowWindow(GetDlgItem(hwnd,IDC_SCROLLVIEW),SW_HIDE);
ShowWindow(GetDlgItem(hwnd,IDC_BUTTON_TITLE),SW_HIDE);
wifiDisConnect();
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief saveConfigCallback 切换wifi开关,保存配置后回调函数
*/
/* ---------------------------------------------------------------------------*/
static void saveConfigCallback(void)
{
showSwichOnOff(form_base->hDlg,g_config.net_config.enable);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief buttonTitleNotify 标题按钮
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ---------------------------------------------------------------------------*/
static void buttonTitleNotify(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc == MYTITLE_BUTTON_EXIT) {
ShowWindow(GetParent(hwnd),SW_HIDE);
// SendMessage(GetParent(hwnd), MSG_CLOSE,0,0);
}
else if (nc == MYTITLE_BUTTON_SWICH) {
g_config.net_config.enable = add_data;
ConfigSavePublicCallback(saveConfigCallback);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief buttonConnect 当wifi连接失败,点击重新连接wifi
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ---------------------------------------------------------------------------*/
static void buttonConnect(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
if (wifi_list_title.enable)
return;
if (connect_wifi_interval == 0) {
connect_wifi_interval = 15; // 连接失败时,每15秒可以重连一次
wifiConnect();
}
}
static void buttonRefresh(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
if (refresh_wifi_interval == 0) {
refresh_wifi_interval = 10; // 连接失败时,每10秒可以重连一次
showSwichOnOff(form_base->hDlg,g_config.net_config.enable);
}
}
static void buttonAdd(HWND hwnd, int id, int nc, DWORD add_data)
{
if (nc != BN_CLICKED)
return;
if (refresh_wifi_interval == 0) {
refresh_wifi_interval = 10; // 连接失败时,每10秒可以重连一次
showSwichOnOff(form_base->hDlg,g_config.net_config.enable);
}
flag_timer_stop = 1;
createFormPassword(form_base->hDlg,NULL,enableAutoClose,getPassword);
}
static void* threadMoveInterval(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
thread_move_start = 1;
while (thread_move_start) {
int div_pos = scro_opt.timer_cur_pos - scro_opt.timer_old_pos;
if (div_pos > 0)
scro_opt.step = div_pos;
else if (div_pos < 0)
scro_opt.step = -div_pos;
else
scro_opt.step = 1;
scro_opt.timer_old_pos = scro_opt.timer_cur_pos;
usleep(20000);
}
return NULL;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief scrollviewInit 重新刷新wifi列表
*/
/* ---------------------------------------------------------------------------*/
static void scrollviewInit(void)
{
scro_opt.cur_pos = 0;
scro_opt.state = BN_UNPUSHED;
GetWindowRect (hScrollView, &scro_opt.rc);
scro_opt.step = 1;
SendMessage(hScrollView,MSG_VSCROLL,SB_THUMBTRACK,scro_opt.cur_pos);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief scrollviewNotify
*
* @param hwnd
* @param id
* @param nc
* @param add_data
*/
/* ---------------------------------------------------------------------------*/
static void scrollviewNotify(HWND hwnd, int id, int nc, DWORD add_data)
{
int idx = SendMessage (hScrollView, SVM_GETCURSEL, 0, 0);
struct ScrollviewItem *plist;
plist = (struct ScrollviewItem *)SendMessage (hScrollView, SVM_GETITEMADDDATA, idx, 0);
if (plist) {
flag_timer_stop = 1;
select_ap.encry = ap_info[idx].encry;
strcpy(select_ap.ssid,ap_info[idx].ssid);
if (select_ap.encry)
createFormPassword(hwnd,select_ap.ssid,enableAutoClose,getPassword);
else {
strcpy(select_ap.ssid,ap_info[idx].ssid);
strcpy(g_config.net_config.ssid,ap_info[idx].ssid);
strcpy(g_config.net_config.security,"NONE");
ConfigSavePublicCallback(saveConfigConnectCallback);
}
// printf("idx:%d,name:%s\n", idx,plist->text);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief formSettingWifiTimerProc1s 1秒定时器,更新wifi连接桩体与强度
*
* @param hwnd
*/
/* ---------------------------------------------------------------------------*/
static void formSettingWifiTimerProc1s(HWND hwnd)
{
// 更新网络状态
static int net_level_old = 0;
int net_level = 0;
if (g_config.net_config.enable) {
if (getWifiConfig(&net_level) != 0)
net_level = 0;
} else
net_level = 0;
wifi_list_title.enable = net_level;
if (net_level != net_level_old) {
updateConnectWifi();
net_level_old = net_level;
}
if (connect_wifi_interval)
connect_wifi_interval--;
if (refresh_wifi_interval)
refresh_wifi_interval--;
}
void formSettingWifiLoadBmp(void)
{
if (bmp_load_finished == 1)
return;
printf("[%s]\n", __FUNCTION__);
bmpsLoad(bmp_load);
bmp_load_finished = 1;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief paint 固定表头绘制函数
*
* @param hWnd
* @param hdc
*/
/* ---------------------------------------------------------------------------*/
static void paint (HWND hWnd, HDC hdc)
{
if (g_config.net_config.enable == 0)
return;
SetPenColor (hdc, 0xCCCCCC);
RECT rcDraw;
SetBkMode (hdc, BM_TRANSPARENT);
SetTextColor (hdc, PIXEL_lightwhite);
SelectFont (hdc, font20);
// 绘制表格
MoveTo (hdc, 0, 90);
LineTo (hdc, 1024,90);
rcDraw.left = 0;
rcDraw.top = 41;
if (wifi_list_title.enable) {
FILL_BMP_STRUCT(rcDraw.left + 33,rcDraw.top + 18,bmp_select);
}
if (wifi_list_title.security) {
FILL_BMP_STRUCT(rcDraw.left + 881,rcDraw.top + 15,bmp_security);
}
if (wifi_list_title.strength < 3)
FILL_BMP_STRUCT(rcDraw.left + 919,rcDraw.top + 15,bmp_wifi[wifi_list_title.strength]);
// FILL_BMP_STRUCT(rcDraw.left + 968,rcDraw.top + 15,bmp_enter);
TextOut (hdc, rcDraw.left + 83, rcDraw.top + 15, wifi_list_title.text);
MoveTo (hdc, 0, 151);
LineTo (hdc, 1024,151);
rcDraw.left = 0;
rcDraw.top = 90;
TextOut (hdc, rcDraw.left + 30, rcDraw.top + 16, "附近网络");
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myDrawItem 列表自定义绘图函数
*
* @param hWnd
* @param hsvi
* @param hdc
* @param rcDraw
*/
/* ---------------------------------------------------------------------------*/
static void myDrawItem (HWND hWnd, HSVITEM hsvi, HDC hdc, RECT *rcDraw)
{
#define DRAW_TABLE(rc,offset) \
do { \
SetPenColor (hdc, 0xCCCCCC); \
if (p_item->index > 0) { \
MoveTo (hdc, rc->left + offset, rc->top); \
LineTo (hdc, rc->right,rc->top); \
} \
MoveTo (hdc, rc->left + offset, rc->bottom); \
LineTo (hdc, rc->right,rc->bottom); \
} while (0)
struct ScrollviewItem *p_item = (struct ScrollviewItem *)scrollview_get_item_adddata (hsvi);
SetBkMode (hdc, BM_TRANSPARENT);
SetTextColor (hdc, PIXEL_lightwhite);
SelectFont (hdc, font20);
if (p_item->enable) {
FILL_BMP_STRUCT(rcDraw->left + 33,rcDraw->top + 18,bmp_select);
}
if (p_item->security) {
FILL_BMP_STRUCT(rcDraw->left + 881,rcDraw->top + 15,bmp_security);
}
if (p_item->strength < 3)
FILL_BMP_STRUCT(rcDraw->left + 919,rcDraw->top + 15,bmp_wifi[p_item->strength]);
FILL_BMP_STRUCT(rcDraw->left + 968,rcDraw->top + 15,bmp_enter);
// 绘制表格
DRAW_TABLE(rcDraw,82);
// 输出文字
TextOut (hdc, rcDraw->left + 83, rcDraw->top + 15, p_item->text);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief wifiLoadData 重新加载wifi列表
*
* @param aps
* @param ap_cnt
*/
/* ---------------------------------------------------------------------------*/
static void wifiLoadData(void *aps,int ap_cnt)
{
TcWifiScan *ap_data = (TcWifiScan *)aps;
int i;
SVITEMINFO svii;
memset(wifi_list,0,sizeof(wifi_list));
SendMessage (hScrollView, SVM_RESETCONTENT, 0, 0);
scro_opt.total_item = ap_cnt;
for (i=0; i < ap_cnt; i++) {
strcpy(wifi_list[i].text,ap_data[i].ssid);
wifi_list[i].index = i;
wifi_list[i].security = (ap_data[i].encry == AWSS_ENC_TYPE_NONE) ? 0 : 1;
// printf("%d,ssi:%s,rssi:%d,security:%d,\n",i,ap_data[i].ssid,ap_data[i].rssi,ap_data[i].encry );
if (ap_data[i].rssi < 2)
wifi_list[i].strength = 0;
else if (ap_data[i].rssi < 4)
wifi_list[i].strength = 1;
else if (ap_data[i].rssi < 6)
wifi_list[i].strength = 2;
if (strcmp(wifi_list_title.text,wifi_list[i].text) == 0) {
wifi_list_title.strength = wifi_list[i].strength;
wifi_list_title.security = wifi_list[i].security;
}
svii.nItemHeight = 60;
svii.addData = (DWORD)&wifi_list[i];
svii.nItem = i;
SendMessage (hScrollView, SVM_ADDITEM, 0, (LPARAM)&svii);
SendMessage (hScrollView, SVM_SETITEMADDDATA, i, (DWORD)&wifi_list[i]);
}
scrollviewInit();
}
/* ----------------------------------------------------------------*/
/**
* @brief initPara 初始化参数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*/
/* ----------------------------------------------------------------*/
static void initPara(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
int i;
for (i=0; ctrls_title[i].idc != 0; i++) {
ctrls_title[i].font = font20;
createMyTitle(hDlg,&ctrls_title[i]);
}
for (i=0; ctrls_button[i].idc != 0; i++) {
ctrls_button[i].font = font22;
createMyButton(hDlg,&ctrls_button[i]);
}
hScrollView = GetDlgItem (hDlg, IDC_SCROLLVIEW);
SendMessage (hScrollView, SVM_SETITEMDRAW, 0, (LPARAM)myDrawItem);
//* 此处不能设置为回调函数,否则第一次返回为-1,minigui bug
// SetNotificationCallback(hScrollView,scrollviewNotify);
scrollviewInit();
SendMessage(GetDlgItem(hDlg,IDC_TITLE),
MSG_MYTITLE_SET_SWICH, (WPARAM)g_config.net_config.enable, 0);
showSwichOnOff(form_base->hDlg,g_config.net_config.enable);
createThread(threadMoveInterval,NULL);
SetTimer(form_base->hDlg,IDC_TIMER_1S,FORM_TIMER_1S);
}
/* ----------------------------------------------------------------*/
/**
* @brief formSettingWifiProc 窗口回调函数
*
* @param hDlg
* @param message
* @param wParam
* @param lParam
*
* @return
*/
/* ----------------------------------------------------------------*/
static int formSettingWifiProc(HWND hDlg, int message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
switch(message) // 自定义消息
{
case MSG_TIMER:
{
if (flag_timer_stop)
return 0;
if (wParam == IDC_TIMER_1S)
formSettingWifiTimerProc1s(hDlg);
} break;
case MSG_SHOWWINDOW:
{
if (wParam == SW_HIDE) {
thread_move_start = 0;
if (IsTimerInstalled(hDlg,IDC_TIMER_1S) == TRUE)
KillTimer (hDlg,IDC_TIMER_1S);
}
}break;
case MSG_COMMAND:
{
scro_opt.notified = 1;
break;
}
case MSG_LBUTTONDOWN:
{
int x, y;
x = LOSWORD(lParam);
y = HISWORD(lParam);
if (GetCapture () == hDlg) {
break;
}
SetCapture (hDlg);
scro_opt.old_pos = y ;
if (PtInRect (&scro_opt.rc, x, y)) {
scro_opt.state = BN_PUSHED;
}
} break;
case MSG_LBUTTONUP:
{
if (scro_opt.moved == 0)
scrollviewNotify(hDlg,IDC_SCROLLVIEW,SVN_CLICKED,0);
if (GetCapture() != hDlg) {
if(scro_opt.state != BN_UNPUSHED) {
scro_opt.state = BN_UNPUSHED;
}
break;
}
ReleaseCapture ();
scro_opt.state = BN_UNPUSHED;
scro_opt.moved = 0;
} break;
case MSG_MOUSEMOVE:
{
scro_opt.timer_cur_pos = HISWORD(lParam);
if (scro_opt.state == BN_PUSHED) {
scro_opt.moved = 1;
if (scro_opt.timer_cur_pos > scro_opt.old_pos)
scro_opt.cur_pos -= scro_opt.step;
else
scro_opt.cur_pos += scro_opt.step;
if (scro_opt.cur_pos < 0)
scro_opt.cur_pos = 0;
// 最大位置为总条目数*条目高度-首页控件高度
if (scro_opt.cur_pos > 60 * scro_opt.total_item - 390)
scro_opt.cur_pos = 60 * scro_opt.total_item - 390;
SendMessage(hScrollView,MSG_VSCROLL,SB_THUMBTRACK,scro_opt.cur_pos);
}
scro_opt.old_pos = scro_opt.timer_cur_pos;
} break;
case MSG_PAINT:
hdc = BeginPaint (hDlg);
paint(hDlg,hdc);
EndPaint (hDlg, hdc);
return 0;
case MSG_ENABLE_WINDOW:
enableAutoClose();
break;
case MSG_DISABLE_WINDOW:
flag_timer_stop = 1;
break;
default:
break;
}
if (form_base->baseProc(form_base,hDlg, message, wParam, lParam) == FORM_STOP)
return 0;
return DefaultDialogProc(hDlg, message, wParam, lParam);
}
int createFormSettingWifi(HWND hMainWnd,void (*callback)(void))
{
HWND Form = Screen.Find(form_base_priv.name);
if(Form) {
Screen.setCurrent(form_base_priv.name);
showSwichOnOff(form_base->hDlg,g_config.net_config.enable);
createThread(threadMoveInterval,NULL);
SetTimer(form_base->hDlg,IDC_TIMER_1S,FORM_TIMER_1S);
ShowWindow(Form,SW_SHOWNORMAL);
scrollviewInit();
} else {
if (bmp_load_finished == 0) {
return 0;
}
form_base_priv.callBack = callback;
form_base = formBaseCreate(&form_base_priv);
return CreateMyWindowIndirectParam(form_base->priv->dlgInitParam,
hMainWnd, form_base->priv->dlgProc, 0);
}
return 0;
}
<file_sep>/src/wireless/tcp_client.c
/*
* =============================================================================
*
* Filename: tcp_client.c
*
* Description: TCP客户端
*
* Version: 1.0
* Created: 2019-06-18 13:41:58
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include "tcp_client.h"
#include "debug.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define TIME_OUT_TIME 3 //connect超时时间
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
TTCPClient* tcp_client;
//---------------------------------------------------------------------------
static void TTCPClient_Destroy(TTCPClient *This) {
if(This->m_socket>0)
This->DisConnect(This);
free(This);
}
//---------------------------------------------------------------------------
static int TTCPClient_Connect(struct _TTCPClient *This,const char *IP,int port,int TimeOut)
{
struct sockaddr_in *p;
struct sockaddr addr;
unsigned long ul = 1;
int ret = 0;
if(This->m_socket)
This->DisConnect(This);
memset(&addr,0,sizeof(addr));
p=(struct sockaddr_in *)&addr;
p->sin_family=AF_INET;
p->sin_port=htons(port);
if(inet_aton(IP,&p->sin_addr)<0)
{
DPRINT("Can't know IP address as %s",IP);
return -1;
}
This->m_socket=socket(PF_INET,SOCK_STREAM,0);
if(This->m_socket==0) {
DPRINT("TCP Client init socket failed!\n");
return -1;
}
if( connect(This->m_socket, &addr,sizeof(addr)) == -1) {
int error=-1, len;
struct timeval tm;
fd_set set;
tm.tv_sec = TimeOut/1000;
tm.tv_usec = (TimeOut%1000)*1000;
FD_ZERO(&set);
FD_SET(This->m_socket, &set);
if( select(This->m_socket+1, NULL, &set, NULL, &tm) > 0) {
getsockopt(This->m_socket, SOL_SOCKET, SO_ERROR, &error, (socklen_t *)&len);
if(error == 0)
ret = 1;
else {
perror("Err: select()");
}
} else {
perror("Err: connect()");
}
} else
ret = 1;
ul = 0;
ioctl(This->m_socket, FIONBIO, &ul); //设置为阻塞模式
if(ret==0) {
This->DisConnect(This);
return -1;
}
return 0;
}
//---------------------------------------------------------------------------
static void TTCPClient_DisConnect(struct _TTCPClient *This)
{
if (This->m_socket)
close(This->m_socket);
This->m_socket = 0;
}
//---------------------------------------------------------------------------
static int TTCPClient_SendBuffer(TTCPClient *This,const void *pBuf,int size)
{
return send(This->m_socket,pBuf,size,MSG_NOSIGNAL);
}
//---------------------------------------------------------------------------
static int TTCPClient_RecvBuffer(TTCPClient *This,void *pBuf,int size,int TimeOut)
{
struct timeval timeout;
fd_set fdR;
int LeaveSize = size;
if(This->m_socket<=0)
return -1;
if(TimeOut<0) {
while(LeaveSize) {
int RecvSize = recv(This->m_socket,((char*)pBuf)+(size-LeaveSize),LeaveSize,MSG_NOSIGNAL);
if(RecvSize<=0)
break;
LeaveSize-=RecvSize;
}
return size-LeaveSize;
}
else
{
while(LeaveSize) {
int RecvSize;
FD_ZERO(&fdR);
FD_SET(This->m_socket, &fdR);
timeout.tv_sec=TimeOut / 1000;
timeout.tv_usec=(TimeOut % 1000) * 1000;
if(select(This->m_socket+1, &fdR,NULL, NULL, &timeout)<=0 || !FD_ISSET(This->m_socket,&fdR)) {
// printf("tcpclient:read select timeout\n");
return -1;
}
RecvSize=recv(This->m_socket,((char*)pBuf)+(size-LeaveSize),LeaveSize,MSG_NOSIGNAL);
if(RecvSize<=0)
break;
LeaveSize-=RecvSize;
}
return size-LeaveSize;
}
}
//---------------------------------------------------------------------------
// 创建一个UDP客户端,Port为0则不绑定端口
//---------------------------------------------------------------------------
TTCPClient* TTCPClient_Create(void)
{
TTCPClient* This;
This = (TTCPClient *)malloc(sizeof(TTCPClient));
if(This==NULL) {
DPRINT("alloc TCPClient memory failt!\n");
return NULL;
}
This->Destroy = TTCPClient_Destroy;
This->RecvBuffer = TTCPClient_RecvBuffer;
This->SendBuffer = TTCPClient_SendBuffer;
This->Connect = TTCPClient_Connect;
This->DisConnect = TTCPClient_DisConnect;
return This;
}
void tcpClientInit(void)
{
tcp_client = TTCPClient_Create();
}
<file_sep>/src/hal/hal_uart.c
/*
* =============================================================================
*
* Filename: hal_uart.c
*
* Description: 硬件层 串口驱动
*
* Version: 1.0
* Created: 2018-12-13 08:44:29
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <strings.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <termios.h> //termios.tcgetattr(),tcsetattr
#include "hal_uart.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define TTY_DEV "/dev/ttyS"
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
static int uartPortSet(int fd, int baudrate, uint8_t data_bit,
uint8_t parity,
uint8_t stop_bit)
{
struct termios termios_old,termios_new;
int tmp;
bzero(&termios_old,sizeof(termios_old));
bzero(&termios_new,sizeof(termios_new));
cfmakeraw(&termios_new);
tcgetattr(fd,&termios_old);
switch(baudrate)
{
case 2400 : baudrate=B2400;break;
case 4800 : baudrate=B4800;break;
case 9600 : baudrate=B9600;break;
case 19200: baudrate=B19200;break;
case 38400: baudrate=B38400;break;
case 57600: baudrate=B57600;break;
case 115200: baudrate=B115200;break;
default: baudrate=B9600;
}
cfsetispeed(&termios_new,baudrate);
cfsetospeed(&termios_new,baudrate);
termios_new.c_cflag |= CLOCAL;
termios_new.c_cflag |= CREAD;
termios_new.c_iflag |= IXON|IXOFF|IXANY;
termios_new.c_cflag&=~CSIZE;
switch(data_bit){
case '5' :
termios_new.c_cflag |= CS5;
case '6' :
termios_new.c_cflag |= CS6;
case '7' :
termios_new.c_cflag |= CS7;
default:
termios_new.c_cflag |= CS8;
}
switch(parity)
{
default:
case '0' :
termios_new.c_cflag &= ~PARENB;
break;
case '1' :
termios_new.c_cflag |= PARENB;
termios_new.c_cflag &=~PARODD;
break;
case '2' :
termios_new.c_cflag |= PARENB;
termios_new.c_cflag |= PARODD;
break;
}
if(stop_bit == '2')
termios_new.c_cflag |= CSTOPB; //2 stop bits
else
termios_new.c_cflag &=~CSTOPB; //1 stop bits
termios_new.c_lflag &=~(ICANON|ECHO|ECHOE|ISIG);
termios_new.c_oflag &= OPOST; //
termios_new.c_cc[VMIN] = 1; //
termios_new.c_cc[VTIME] = 0; //
termios_new.c_lflag &= (ICANON|ECHO|ECHOE|ISIG);
tcflush(fd,TCIFLUSH); //
tmp = tcsetattr(fd,TCSANOW,&termios_new); //
tcgetattr(fd,&termios_old);
return(tmp);
}
int halUartOpen(int com,
int baudrate,
uint8_t data_bit,
uint8_t parity,
uint8_t stop_bit,
void *callback_func)
{
int fd;
char *ptty;
#if (defined X86)
return 0;
#else
switch(com){
case 0:
ptty = TTY_DEV"0";
break;
case 1:
ptty = TTY_DEV"1";
break;
case 2:
ptty = TTY_DEV"2";
break;
default:
ptty = TTY_DEV"3";
break;
}
fd = open(ptty,O_RDWR|O_NOCTTY|O_NONBLOCK|O_NDELAY);
if (fd)
uartPortSet(fd,baudrate,data_bit,parity,stop_bit);
return fd;
#endif
}
int halUartRead(int fd,void *buf,uint32_t size)
{
#if (defined X86)
return 0;
#else
return read(fd,buf,size);
#endif
}
int halUartWrite(int fd,void *buf,uint32_t size)
{
#if (defined X86)
return 0;
#else
return write(fd,buf,size);
#endif
}
<file_sep>/include/RK_VOICE_ProInterface.h
/************************************************************************************
文件名称:
文件功能:
函数列表:
修改日期:
*************************************************************************************/
#ifndef RK_VOICE_PROINTERFACE_H
#define RK_VOICE_PROINTERFACE_H
/*--------------------------------------- include -----------------------------------*/
#ifdef __cplusplus
extern "C" {
#endif
/*--------------------------------------- 宏定义 -----------------------------------------*/
/*--------------------------------------- 枚举定义 ----------------------------------------*/
/*--------------------------------------- 结构体定义 --------------------------------------*/
/*-------------------------------------- 全局变量声明 --------------------------------------*/
/*----------------------------------------- 函数声明 ---------------------------------------*/
extern short int VOICE_Init(short int *pshwPara);
extern void VOICE_ProcessTx(short int *pshwIn,
short int *pshwRef,
short int *pshwOut,
int swFrmLen);
extern void VOICE_ProcessRx(short int *pshwIn,
short int *pshwOut,
int swFrmLen);
extern void VOICE_Destory();
#ifdef __cplusplus
}
#endif
#endif
<file_sep>/src/gui/my_controls/my_battery.h
/*
* =============================================================================
*
* Filename: my_battery.h
*
* Description: 自定义静态控件
*
* Version: 1.0
* Created: 2019-04-23 19:46:14
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_BATTERY_H
#define _MY_BATTERY_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include "my_controls.h"
#include "commongdi.h"
#define CTRL_MYBATTERY ("mybattery")
enum {
MSG_SET_QUANTITY = MSG_USER + 1,
MSG_SET_STATUS,
};
typedef struct {
int ele_quantity; // 电量
PLOGFONT font; // 字体
int state; // 状态,0正常,1充电
}MyBatteryCtrlInfo;
typedef struct _MyCtrlBattery{
HWND idc; // 控件ID
int16_t x,y,w,h;
PLOGFONT font; // 字体
int ele_quantity; // 电量
int state; // 状态,0正常,1充电
}MyCtrlBattery;
HWND createMyBattery(HWND hWnd,MyCtrlBattery *);
extern MyControls *my_battery;
void initMyBattery(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/video/CMakeLists.txt
STRING( REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER_APP_VIDEO ${CMAKE_CURRENT_SOURCE_DIR})
set(SRC_APP_VIDEO
video_server.cpp
h264_enc_dec/mpi_dec_api.c
h264_enc_dec/mpp_dec_test.cpp
h264_enc_dec/mpi_enc_api.c
h264_enc_dec/h264_split.c
camera/camerahal.cpp
buffer/camerabuf.cpp
process/display_process.cpp
process/face_process.cpp
process/encoder_process.cpp
)
add_definitions(
-DLINUX -DSUPPORT_ION -DENABLE_ASSERT -DDEBUG
)
add_definitions(-DLIBION)
add_library (${CURRENT_FOLDER_APP_VIDEO} ${SRC_APP_VIDEO})
target_link_libraries(${CURRENT_FOLDER_APP_VIDEO}
ion pthread adk cam_ia cam_engine_cifisp rkfb rkrga
yuv
easymedia mpp
)
<file_sep>/src/app/config.c
#include <sys/ioctl.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include "externfunc.h"
#include "thread_helper.h"
#include "config.h"
#include "sql_handle.h"
#include "protocol.h"
#include "debug.h"
#define SIZE_CONFIG(x) x,sizeof(x) - 1
#define NELEMENTS(array) (sizeof (array) / sizeof ((array) [0]))
Config g_config;
struct SaveType {
int cmd; // 0 private, 1public
configCallback func; // 回调函数
};
static dictionary* cfg_public_ini;
static dictionary* cfg_private_ini;
static pthread_mutex_t cfg_mutex ;
static EtcValueInt etc_public_int[]={
{"cloud", "timestamp", &g_config.timestamp, 0},
{"wireless", "enable", &g_config.net_config.enable,0},
{"cap_doorbell","type", &g_config.cap_doorbell.type, 0},
{"cap_doorbell","count", &g_config.cap_doorbell.count, 1},
{"cap_doorbell","timer", &g_config.cap_doorbell.timer, 5},
{"cap_alarm", "type", &g_config.cap_alarm.type, 0},
{"cap_alarm", "count", &g_config.cap_alarm.count, 1},
{"cap_alarm", "timer", &g_config.cap_alarm.timer, 5},
{"cap_talk", "type", &g_config.cap_talk.type, 0},
{"cap_talk", "count", &g_config.cap_talk.count, 1},
{"cap_talk", "timer", &g_config.cap_talk.timer, 10},
{"rings", "ring_num", &g_config.ring_num, 0},
{"rings", "ring_volume", &g_config.ring_volume, 80},
{"rings", "alarm_volume", &g_config.alarm_volume, 80},
{"rings", "talk_volume", &g_config.talk_volume, 80},
{"rings", "mute_state", &g_config.mute.state, 0},
{"rings", "mute_start_time", &g_config.mute.start_time, 0},
{"rings", "mute_end_time", &g_config.mute.end_time, 1439},
{"others", "pir_active_times", &g_config.pir_active_timer, 40},
{"others", "pir_alarm", &g_config.pir_alarm, 0},
{"others", "pir_strength", &g_config.pir_strength, 1},
{"others", "screensaver_time", &g_config.screensaver_time, 11},
{"others", "brightness", &g_config.brightness, 50},
{"others", "record_time", &g_config.record_time, 30},
{"others", "auto_sync_time", &g_config.auto_sync_time, 1},
{"others", "face_enable", &g_config.face_enable, 1},
{"others", "sleep_time", &g_config.sleep_time, 20},
};
static EtcValueChar etc_public_char[]={
{"device", "version", SIZE_CONFIG(g_config.version), DEVICE_SVERSION},
{"cloud", "app_url", SIZE_CONFIG(g_config.app_url), "123"},
{"wireless", "ssid", SIZE_CONFIG(g_config.net_config.ssid), "MINI"},
{"wireless", "mode", SIZE_CONFIG(g_config.net_config.mode), "Infra"},
{"wireless", "security", SIZE_CONFIG(g_config.net_config.security), "WPA/WPA2 PSK"},
{"wireless", "password", SIZE_CONFIG(g_config.net_config.password), "<PASSWORD>"},
{"wireless", "running", SIZE_CONFIG(g_config.net_config.running), "station"},
};
static EtcValueChar etc_private_char[]={
{"device", "imei", SIZE_CONFIG(g_config.imei), "0"},
{"face", "license", SIZE_CONFIG(g_config.f_license),"0"},
};
static char *sec_private[] = {
"device",
"face",
NULL
};
static char *sec_public[] = {
"device",
"cloud",
"wireless",
"rings",
"cap_doorbell",
"cap_alarm",
"cap_talk",
"others",
NULL
};
void configSync(void)
{
sync();
}
static int etcFileCheck(void)
{
const char * buf = iniparser_getstring(cfg_private_ini, "taichuan:imei", "0");
if (strcmp(buf,"0") == 0) {
recoverData(CONFIG_FILENAME);
return 0;
} else {
return 1;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief configoadEtcInt 加载int型配置文件
*
* @param etc_file 文件数组地址
* @param length 数组长度
*/
/* ---------------------------------------------------------------------------*/
static void configLoadEtcInt(dictionary *cfg_ini, EtcValueInt *etc_file,
unsigned int length)
{
unsigned int i;
char buf[64];
for (i=0; i<length; i++) {
sprintf(buf,"%s:%s",etc_file->section,etc_file->key);
*etc_file->value = iniparser_getint(cfg_ini, buf, etc_file->default_int);
printf("[%s]%s,%d\n", __FUNCTION__,buf,*etc_file->value);
etc_file++;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief configResetEtcInt 恢复默认配置
*
* @param etc_file
* @param length
*/
/* ---------------------------------------------------------------------------*/
static void configResetEtcInt(EtcValueInt *etc_file, unsigned int length)
{
unsigned int i;
for (i=0; i<length; i++) {
*etc_file->value = etc_file->default_int;
etc_file++;
}
}
static void configResetEtcChar(EtcValueChar *etc_file,
unsigned int length)
{
unsigned int i;
for (i=0; i<length; i++) {
strncpy(etc_file->value, etc_file->default_char, etc_file->leng);
etc_file++;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief configLoadEtcChar 加载char型配置文件
*
* @param etc_file 文件数组地址
* @param length 数组长度
*/
/* ---------------------------------------------------------------------------*/
void configLoadEtcChar(dictionary *cfg_ini, EtcValueChar *etc_file,
unsigned int length)
{
unsigned int i;
char buf[64];
for (i=0; i<length; i++) {
sprintf(buf,"%s:%s",etc_file->section,etc_file->key);
strncpy(etc_file->value,
iniparser_getstring(cfg_ini, buf, etc_file->default_char),
etc_file->leng);
// DPRINT("[%s]%s,%s\n", __FUNCTION__,buf,etc_file->value);
etc_file++;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief configSaveEtcInt 加载int型配置文件
*
* @param etc_file 文件数组地址
* @param length 数组长度
*/
/* ---------------------------------------------------------------------------*/
static void configSaveEtcInt(dictionary *cfg_ini, EtcValueInt *etc_file,
unsigned int length)
{
unsigned int i;
char buf[64];
char data[64];
for (i=0; i<length; i++) {
sprintf(buf,"%s:%s",etc_file->section,etc_file->key);
sprintf(data,"%d",*etc_file->value);
iniparser_set(cfg_ini, buf, data);
etc_file++;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief configSaveEtcChar 加载char型配置文件
*
* @param etc_file 文件数组地址
* @param length 数组长度
*/
/* ---------------------------------------------------------------------------*/
static void configSaveEtcChar(dictionary *cfg_ini, EtcValueChar *etc_file,
unsigned int length)
{
unsigned int i;
char buf[64];
for (i=0; i<length; i++) {
sprintf(buf,"%s:%s",etc_file->section,etc_file->key);
// DPRINT("[%d]iniparser_set:%s--%s\n",i,buf,etc_file->value );
iniparser_set(cfg_ini, buf, etc_file->value);
etc_file++;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief dumpIniFile iniparser_dump_ini 配置
*
* @param d
* @param file_name
*/
/* ---------------------------------------------------------------------------*/
static void dumpIniFile(dictionary *d,char *file_name)
{
FILE* f;
// save to file
f = fopen(file_name, "wb");
if (!f) {
DPRINT("cannot open ini file: %s\n", file_name);
return;
}
iniparser_dump_ini(d, f);
fflush(f);
fclose(f);
}
static void SavePrivate(void)
{
configSaveEtcChar(cfg_private_ini,etc_private_char,NELEMENTS(etc_private_char));
dumpIniFile(cfg_private_ini,CONFIG_FILENAME);
if (etcFileCheck() == 1) {
backData(CONFIG_FILENAME);
}
DPRINT("[%s]end\n", __FUNCTION__);
}
static void SavePublic(void)
{
configSaveEtcInt(cfg_public_ini,etc_public_int,NELEMENTS(etc_public_int));
configSaveEtcChar(cfg_public_ini,etc_public_char,NELEMENTS(etc_public_char));
dumpIniFile(cfg_public_ini,CONFIG_PARA_FILENAME);
if (etcFileCheck() == 1) {
backData(CONFIG_PARA_FILENAME);
}
DPRINT("[%s]end\n", __FUNCTION__);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief loadIniFile 加载ini文件,同时检测字段完整性
*
* @param d
* @param file_path
* @param sec[]
*
* @returns >0 有缺少字段,需要保存更新, 0无缺少字段,正常
*/
/* ---------------------------------------------------------------------------*/
static int loadIniFile(dictionary **d,char *file_path,char *sec[])
{
int ret = 0;
int i;
*d = iniparser_load(file_path);
if (*d == NULL) {
*d = dictionary_new(0);
assert(*d);
ret++;
for (i=0; sec[i] != NULL; i++)
iniparser_set(*d, sec[i], NULL);
} else {
int nsec = iniparser_getnsec(*d);
int j;
const char * secname;
for (i=0; sec[i] != NULL; i++) {
for (j=0; j<nsec; j++) {
secname = iniparser_getsecname(*d, j);
if (strcasecmp(secname,sec[i]) == 0)
break;
}
if (j == nsec) {
ret++;
iniparser_set(*d, sec[i], NULL);
}
}
}
return ret;
}
void createSdcardDirs(void)
{
if (checkSD() == -1)
return;
mkdir(CAP_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
mkdir(TALK_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
mkdir(ALARM_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
mkdir(FACE_PATH, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
void configLoad(void)
{
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&cfg_mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
int ret = loadIniFile(&cfg_private_ini,CONFIG_FILENAME,sec_private);
configLoadEtcChar(cfg_private_ini,etc_private_char,NELEMENTS(etc_private_char));
etcFileCheck();
if (ret)
SavePrivate();
ret = loadIniFile(&cfg_public_ini,CONFIG_PARA_FILENAME,sec_public);
configLoadEtcChar(cfg_public_ini,etc_public_char,NELEMENTS(etc_public_char));
configLoadEtcInt(cfg_public_ini,etc_public_int,NELEMENTS(etc_public_int));
if (ret || strcmp(g_config.version,DEVICE_SVERSION) != 0) {
strcpy(g_config.version,DEVICE_SVERSION);
SavePublic();
}
getCpuId(g_config.hardcode);
getKernelVersion(g_config.k_version,sizeof(g_config.k_version));
printf("imei:%s,hard:%s\n", g_config.imei,g_config.hardcode);
#if 0
// 手动生成二维码图片
char buf[128] = {0};
sprintf(buf,"%s/%s",g_config.imei,g_config.hardcode);
qrcodeString(buf,QRCODE_IMIE);
#endif
createSdcardDirs();
}
static void* ConfigSaveTask(void* arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
pthread_mutex_lock(&cfg_mutex);
struct SaveType *save_type = (struct SaveType *)arg;
if (save_type->cmd == 0)
SavePrivate();
else if (save_type->cmd == 1)
SavePublic();
configSync();
if(save_type->func)
save_type->func();
pthread_mutex_unlock(&cfg_mutex);
return NULL;
}
void ConfigSavePrivate(void)
{
static struct SaveType save_type = { 0,NULL };
createThread(ConfigSaveTask, &save_type);
}
void ConfigSavePrivateCallback(configCallback func)
{
static struct SaveType save_type = { 0, NULL };
save_type.func = func;
createThread(ConfigSaveTask, &save_type);
}
void ConfigSavePublic(void)
{
static struct SaveType save_type = { 1,NULL };
createThread(ConfigSaveTask, &save_type);
}
void ConfigSavePublicCallback(configCallback func)
{
static struct SaveType save_type = { 1, NULL };
save_type.func = func;
createThread(ConfigSaveTask, &save_type);
}
static void configFactoryCallback(void)
{
screenSetBrightness(g_config.brightness);
protocol_singlechip->cmdSetPirStrength(g_config.pir_strength);
sqlClearAll();
}
void configFactory(void)
{
ReportFactory factory_data;
configResetEtcInt(etc_public_int,NELEMENTS(etc_public_int));
configResetEtcChar(etc_public_char,NELEMENTS(etc_public_char));
getDate(factory_data.date,sizeof(factory_data.date));
protocol_hardcloud->reportFactory(&factory_data);
ConfigSavePublicCallback(configFactoryCallback);
}
<file_sep>/src/app/protocol_singlechip.c
/*
* =============================================================================
*
* Filename: protocol_singlechip.c
*
* Description: 单片机通信协议
*
* Version: 1.0
* Created: 2019-06-10 13:11:39
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "debug.h"
#include "uart.h"
#include "config.h"
#include "protocol.h"
#include "sql_handle.h"
#include "my_video.h"
#include "my_audio.h"
#include "externfunc.h"
#include "gui/screen.h"
#include "jpeg_enc_dec.h"
#include "thread_helper.h"
#include "form_videolayer.h"
#include "ipc_server.h"
#include "sensor_detector.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
extern void screenAutoCloseStop(void);
extern void topMsgDoorbell(void);
extern IpcServer* ipc_main;
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define PIR_TIMER_INTERVAL 10
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
ProtocolSinglechip *protocol_singlechip;
// 从触发到未触发转变,需要经过一定时间等待稳定后才重新开始计数
static int pir_act_count = 0; // PIR传感器连续触发倒计时,若3s内没有再次触发,则进入未触发倒计时
static int pir_act_timer = 0; // PIR传感器触发倒计时,10秒内没有触发,清零
static int pir_disact_timer = 0; // PIR传感器触发倒计时,10秒内没有触发,清零
static int pir_cycle_end = 0; // PIR触发周期结束,一个周期内,只触发一次人脸或抓拍
static uint64_t picture_id = 0;
static void cmdSleep(void)
{
#ifdef AUTO_SLEEP
IpcData ipc_data;
ipc_data.dev_type = IPC_DEV_TYPE_MAIN;
ipc_data.cmd = IPC_UART_SLEEP;
if (ipc_main)
ipc_main->sendData(ipc_main,IPC_UART,&ipc_data,sizeof(ipc_data));
#endif
}
static void cmdPowerOff(void)
{
IpcData ipc_data;
ipc_data.dev_type = IPC_DEV_TYPE_MAIN;
ipc_data.cmd = IPC_UART_POWEROFF;
if (ipc_main)
ipc_main->sendData(ipc_main,IPC_UART,&ipc_data,sizeof(ipc_data));
}
static void cmdWifiReset(void)
{
IpcData ipc_data;
ipc_data.dev_type = IPC_DEV_TYPE_MAIN;
ipc_data.cmd = IPC_UART_WIFI_RESET;
if (ipc_main)
ipc_main->sendData(ipc_main,IPC_UART,&ipc_data,sizeof(ipc_data));
}
static void cmdGetVersion(void)
{
IpcData ipc_data;
ipc_data.dev_type = IPC_DEV_TYPE_MAIN;
ipc_data.cmd = IPC_UART_GETVERSION;
if (ipc_main)
ipc_main->sendData(ipc_main,IPC_UART,&ipc_data,sizeof(ipc_data));
}
static void cmdSetPirStrength(int strength)
{
IpcData ipc_data;
ipc_data.dev_type = IPC_DEV_TYPE_MAIN;
ipc_data.cmd = IPC_UART_SET_PIR;
ipc_data.pir_strength = strength;
if (ipc_main)
ipc_main->sendData(ipc_main,IPC_UART,&ipc_data,sizeof(ipc_data));
}
static void* threadPirTimer(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
while (1) {
if (pir_act_timer) {
// printf("[%s]act:%d\n", __func__,pir_act_timer);
if (--pir_act_timer == 0 ) {
pir_disact_timer = PIR_TIMER_INTERVAL;
}
}
if (pir_disact_timer) {
// printf("[%s]disact:%d\n", __func__,pir_disact_timer);
if (--pir_disact_timer == 0) {
pir_act_count = 0;
pir_cycle_end = 0;
}
}
sleep(1);
}
return NULL;
}
static void deal(IpcData *ipc_data)
{
switch(ipc_data->cmd)
{
case IPC_UART_KEY_POWER:
screensaverSet(0);
screenAutoCloseStop();
Screen.ReturnMain();
break;
case IPC_UART_KEYHOME:
screensaverSet(1);
formVideoLayerScreenOn();
break;
case IPC_UART_CAPTURE:
{
if (pir_cycle_end == 1)
break;
pir_cycle_end = 1;
char url[256] = {0};
picture_id = atoll(ipc_data->data.file.name);
sprintf(url,"%s/%s_%s_0.jpg",QINIU_URL,g_config.imei,ipc_data->data.file.name);
sqlInsertRecordCapNoBack(ipc_data->data.file.date,picture_id);
sqlInsertPicUrlNoBack(picture_id,url);
protocol_hardcloud->uploadPic(FAST_PIC_PATH,picture_id);
protocol_hardcloud->reportCapture(picture_id);
}
case IPC_UART_DOORBELL:
{
if (my_video->isTalking())
topMsgDoorbell();
else if (ipc_data->need_ring){
if (isNeedToPlay())
myAudioPlayDindong();
}
formVideoLayerScreenOn();
my_video->videoCallOutAll();
if (pir_cycle_end == 1)
break;
pir_cycle_end = 1;
my_video->capture(CAP_TYPE_DOORBELL,g_config.cap_doorbell.count,NULL,NULL);
}
break;
case IPC_UART_POWEROFF:
formVideoLayerGotoPoweroff();
break;
case IPC_UART_PIR:
my_video->delaySleepTime(0);
pir_act_timer = PIR_TIMER_INTERVAL;
pir_disact_timer = 0;
if (my_video->isVideoOn())
break;
if (pir_cycle_end == 1)
break;
// PIR连续触发为2秒一次,比如触发10秒需要5次,所以需要除2
if (++pir_act_count == (g_config.pir_active_timer / 2)) {
pir_cycle_end = 1;
if (g_config.cap_alarm.type == 0)
my_video->capture(CAP_TYPE_ALARM,g_config.cap_alarm.count,NULL,NULL);
else {
// 录像
}
}
break;
case IPC_UART_GETVERSION:
strcpy(g_config.s_version,ipc_data->s_version);
break;
case IPC_UART_SET_PIR:
printf("set pir result:%d\n", ipc_data->pir_strength_result);
break;
default:
break;
}
}
static void hasPeople(char *nick_name,char *user_id)
{
if (pir_cycle_end == 1)
return;
pir_cycle_end = 1;
my_video->capture(CAP_TYPE_FACE,1,nick_name,user_id);
}
void registSingleChip(void)
{
protocol_singlechip = (ProtocolSinglechip *) calloc(1,sizeof(ProtocolSinglechip));
protocol_singlechip->cmdSleep = cmdSleep;
protocol_singlechip->cmdPowerOff = cmdPowerOff;
protocol_singlechip->cmdWifiReset = cmdWifiReset;
protocol_singlechip->cmdGetVersion = cmdGetVersion;
protocol_singlechip->cmdSetPirStrength = cmdSetPirStrength;
protocol_singlechip->deal = deal;
protocol_singlechip->hasPeople = hasPeople;
createThread(threadPirTimer,NULL);
protocol_singlechip->cmdGetVersion();
protocol_singlechip->cmdSetPirStrength(g_config.pir_strength);
}
<file_sep>/src/app/udp_talk/udp_client.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "udp_client.h"
//---------------------------------------------------------------------------
static void TUDPClient_Destroy(TUDPClient *This)
{
if(This->m_socket>0)
close(This->m_socket);
free(This);
This = NULL;
}
//---------------------------------------------------------------------------
void TUDPClient_ClearBuffer(TUDPClient *This)
{
char cBuf[1000];
while(This->RecvBuffer(This,cBuf,1000,0,0,0)>0);
}
//---------------------------------------------------------------------------
static int TUDPClient_SendBuffer(TUDPClient *This,const char *IP,int port,const void *pBuf,int size)
{
struct sockaddr_in *p;
struct sockaddr addr;
struct hostent *hostaddr;
if(This->m_socket<0)
return -1;
if(IP[0]==0 || port==0)
return -2;
memset(&addr,0,sizeof(addr));
p=(struct sockaddr_in *)&addr;
p->sin_family=AF_INET;
p->sin_port=htons(port);
if(IP[0]<'0' || IP[0]>'9') {
hostaddr = gethostbyname(IP);
if(!hostaddr)
{
printf("Parse address %s fail!\n",IP);
return -3;
}
memcpy(&p->sin_addr,hostaddr->h_addr,hostaddr->h_length);
} else {
p->sin_addr.s_addr = inet_addr(IP);
if((p->sin_addr.s_addr == INADDR_NONE) && (strcmp(IP,"255.255.255.255")!=0))
{
printf("IP Address %s Error\n",IP);
return -4;
}
}
return sendto(This->m_socket,(char*)pBuf,size,MSG_NOSIGNAL,&addr,sizeof(struct sockaddr_in));
}
//---------------------------------------------------------------------------
static int TUDPClient_RecvBuffer(TUDPClient *This,void *pBuf,int size,int TimeOut,
void *from,int * fromlen)
{
struct timeval timeout;
fd_set fdR;
if(This->m_socket<0)
return -1;
if(TimeOut<0)
return recvfrom(This->m_socket,(char*)pBuf,size,MSG_NOSIGNAL,(struct sockaddr *)from,fromlen);
else
{
FD_ZERO(&fdR);
FD_SET(This->m_socket, &fdR);
timeout.tv_sec=TimeOut / 1000;
timeout.tv_usec=(TimeOut % 1000)<<10;
if(select(This->m_socket+1, &fdR,NULL, NULL, &timeout)<=0 || !FD_ISSET(This->m_socket,&fdR))
return -1;
return recvfrom(This->m_socket,(char*)pBuf,size,MSG_NOSIGNAL,(struct sockaddr *)from,fromlen);
}
}
//---------------------------------------------------------------------------
// 创建一个UDP客户端,Port为0则不绑定端口
//---------------------------------------------------------------------------
TUDPClient* TUDPClient_Create(int Port)
{
int ret;
TUDPClient* This;
struct sockaddr_in local_addr;
int opt=1;
This = (TUDPClient *)malloc(sizeof(TUDPClient));
if(This==NULL) {
printf("alloc UDPClient memory failt!\n");
return NULL;
}
memset(&local_addr,0,sizeof(local_addr));
This->m_socket=socket(AF_INET,SOCK_DGRAM,0);
if(This->m_socket<0) {
printf("UDP Client init socket failed!\n");
free(This);
return NULL;
}
// int recvbuff = 1*1024*1024;
ret = setsockopt(This->m_socket,SOL_SOCKET,SO_BROADCAST,(char*)&opt,sizeof(opt));
if(ret!=0) {
printf("setsockopt error %d\n",ret);
}
if(Port)
{
local_addr.sin_family = AF_INET;
local_addr.sin_port = htons(Port);
local_addr.sin_addr.s_addr = INADDR_ANY;
if(bind(This->m_socket, (struct sockaddr *)&local_addr, sizeof(struct sockaddr))<0)
{
printf("UDP client bind to port failed!:%d\n",Port);
close(This->m_socket);
free(This);
return NULL;
}
}
This->Destroy = TUDPClient_Destroy;
This->Clear = TUDPClient_ClearBuffer;
This->RecvBuffer = TUDPClient_RecvBuffer;
This->SendBuffer = TUDPClient_SendBuffer;
return This;
}
//---------------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////////////
<file_sep>/src/drivers/sqlite.h
#ifndef LOCALSQLCONNECTH
#define LOCALSQLCONNECTH
#ifndef FALSE
#define FALSE 0
#define TRUE 1
#define BOOL int
#endif
//----------------------------------------------------------------------------
struct SqlitePrivate; //私有数据
#define SQL_NAME_MAX 32
typedef struct _TSQLiteField
{
struct SqlitePrivate *Private;
char Name[SQL_NAME_MAX]; //字段名
int offset; //第几个字段
char * (*AsChar)(struct _TSQLiteField *This,char *Buf,int Size); //作为字段型读取
int (*AsInt)(struct _TSQLiteField *This); //作为整型读取
double (*AsFloat)(struct _TSQLiteField *This); //作为浮点型读取
} TSQLiteField,*PSQLiteField;
//----------------------------------------------------------------------------
struct Sqlite_mutex;
typedef struct _TSqlite
{
struct SqlitePrivate * Private;
PSQLiteField Fields;
char ServerIP[16];
int ServerPort;
const char *file_name;
struct Sqlite_mutex *sql_lock;
void (*Destroy)(struct _TSqlite *This); //销毁
BOOL (*Open)(struct _TSqlite *This); //打开
BOOL (*ExecSQL)(struct _TSqlite *This); //执行
void (*Close)(struct _TSqlite *This); //关闭
void (*First)(struct _TSqlite *This); //首记录
void (*Last)(struct _TSqlite *This); //末记录
void (*Prior)(struct _TSqlite *This); //上一记录
void (*Next)(struct _TSqlite *This); //下一记录
void (*SetRecNo)(struct _TSqlite *This,int RecNo); //跳到记录号
int (*RecNo)(struct _TSqlite *This); //返回记录号
PSQLiteField (*FieldByName)(struct _TSqlite *This,char *Name); //返回字段
int (*GetSQLText)(struct _TSqlite *This,char *pBuf,int Size); //取SQL命令行
void (*SetSQLText)(struct _TSqlite *This,char *SqlCmd); //设置SQL命令行
BOOL (*Active)(struct _TSqlite *This); //是否打开表
int (*RecordCount)(struct _TSqlite *This); //读行数
int (*FieldCount)(struct _TSqlite *This); //字段数
int (*LastRowId)(struct _TSqlite *This); //取得最后插入影响的ID
void (*prepare)(struct _TSqlite *This,char *SqlCmd);
void (*bind_reset)(struct _TSqlite *This);
void (*get_reset)(struct _TSqlite *This);
void (*finalize)(struct _TSqlite *This);
int (*step)(struct _TSqlite *This);
void (*bind_int)(struct _TSqlite *This,int arg);
void (*bind_text)(struct _TSqlite *This,char *text);
void (*bind_blob)(struct _TSqlite *This,void *data,int size);
void (*getBlobData)(struct _TSqlite *This,void *data);
void (*getBindText)(struct _TSqlite *This,char *data);
} TSqlite;
typedef struct _TSqliteData {
const char *file_name;
TSqlite *sql;
int (*checkFunc)(TSqlite *sql);
}TSqliteData;
TSqlite * CreateLocalQuery(const char *FileName);
void LocalQueryLoad(TSqliteData *sql);
BOOL LocalQueryOpen(TSqlite *Query,char *SqlStr);
BOOL LocalQueryExec(TSqlite *Query,char *SqlStr);
char* LocalQueryOfChar(TSqlite *Query,char *FieldName,char *cBuf,int Size);
int LocalQueryOfInt(TSqlite *Query,char *FieldName);
double LocalQueryOfFloat(TSqlite *Query,char *FieldName);
//----------------------------------------------------------------------------
#endif
<file_sep>/src/app/video/h264_enc_dec/mpi_enc_api.h
/*
* =============================================================================
*
* Filename: mpi_enc_api.h
*
* Description: mpp api h264编码
*
* Version: 1.0
* Created: 2019-06-20 15:51:26
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MPI_ENC_API_H
#define _MPI_ENC_API_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
struct _H264EncodePriv;
typedef struct _H264Encode {
struct _H264EncodePriv *priv;
int (*encode)(struct _H264Encode *This,
unsigned char *in_data,
unsigned char **out_data,
int *frame_type);
void (*init)(struct _H264Encode *This,int w,int h);
void (*unInit)(struct _H264Encode *This);
}H264Encode;
H264Encode *my_h264enc;
void myH264EncInit(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/drivers/playwav.h
/*
* =====================================================================================
*
* Filename: playwav.h
*
* Description: .wav文件播放驱动
*
* Version: 1.0
* Created: 2015-11-24 14:23:39
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
#ifndef _PLAY_WAV_H
#define _PLAY_WAV_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
int playwavfile(char * file_name);
void playWavStop();
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/video/camera/camerahal.h
#ifndef __CAMERA_HAL_H__
#define __CAMERA_HAL_H__
#include "camera_factory.h"
#include "camerabuf.h"
#include "display_process.h"
class RKCameraHal {
public:
int type(void) {
return type_;
}
int index(void) {
return index_;
}
virtual frm_info_t& format(void) {
return format_;
}
RKCameraHal(std::shared_ptr<CamHwItf> dev, int index, int type);
~RKCameraHal();
void init(const uint32_t width, const uint32_t height, const int fps);
void start(const uint32_t num, std::shared_ptr<RKCameraBufferAllocator> ptr_allocator);
void stop(void);
std::shared_ptr<CamHwItf::PathBase>& mpath(void) {
return mpath_;
}
std::shared_ptr<CamHwItf> camdev;
std::shared_ptr<CamHwItf::PathBase> mpath_;
int type_;
int index_;
frm_info_t format_;
};
#endif // __CAMERA_HAL_H__<file_sep>/src/drivers/iniparser/CMakeLists.txt
# 查找当前目录下的所有源文件 并将名称保存到 SRCS_INIPARSER 变量
aux_source_directory(. SRCS_INIPARSER)
STRING( REGEX REPLACE ".*/(.*)" "\\1" CURRENT_FOLDER_INIPARSER ${CMAKE_CURRENT_SOURCE_DIR})
# 生成链接库
add_library (${CURRENT_FOLDER_INIPARSER} ${SRCS_INIPARSER})
<file_sep>/src/CMakeLists.txt
# 查找当前目录下的所有源文件
# 并将名称保存到 EXE_SRCS 变量
aux_source_directory(. EXE_SRCS)
# 增加子目录,增加此目录
set(SUB_DIRS
app
gui
wireless
drivers
hal
)
foreach(sub ${SUB_DIRS})
add_subdirectory(${sub})
endforeach()
add_executable(${EXE} ${EXE_SRCS})
# 链接库
target_link_libraries (${EXE}
-Wl,--start-group
${SUB_DIRS}
sqlite3 qrencode paho-mqtt3a ssl curl cjson crypto
minigui_ths png12 png jpeg freetype turbojpeg
z m dl rt
-Wl,--end-group
)
if (PLATFORM_RV1108)
target_link_libraries (${EXE}
ts
rkrga rkfb ion yuv stdc++
voice_process )
endif()
<file_sep>/src/app/my_ntp.h
/*
* =============================================================================
*
* Filename: my_ntp.h
*
* Description: 同步时间接口
*
* Version: 1.0
* Created: 2019-05-21 16:54:10
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_NTPTIME_H
#define _MY_NTPTIME_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
void ntpTime(char *server_ip,void (*callBack)(void));
void ntpEnable(int enable);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/gui/my_controls/my_button.c
/*
* =====================================================================================
*
* Filename: MyButton.c
*
* Description: 自定义按钮
*
* Version: 1.0
* Created: 2015-12-09 16:22:37
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
/* ----------------------------------------------------------------*
* include head files
*-----------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include "my_button.h"
#include "debug.h"
#include "cliprect.h"
#include "internals.h"
#include "ctrlclass.h"
/* ----------------------------------------------------------------*
* extern variables declare
*-----------------------------------------------------------------*/
/* ----------------------------------------------------------------*
* internal functions declare
*-----------------------------------------------------------------*/
static int myButtonControlProc (HWND hwnd, int message, WPARAM wParam, LPARAM lParam);
/* ----------------------------------------------------------------*
* macro define
*-----------------------------------------------------------------*/
#define CTRL_NAME CTRL_MYBUTTON
/* ----------------------------------------------------------------*
* variables define
*-----------------------------------------------------------------*/
MyControls *my_button;
/* ---------------------------------------------------------------------------*/
/**
* @brief myButtonRegist 注册控件
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static BOOL myButtonRegist (void)
{
WNDCLASS WndClass;
WndClass.spClassName = CTRL_NAME;
WndClass.dwStyle = WS_NONE;
WndClass.dwExStyle = WS_EX_NONE;
WndClass.hCursor = GetSystemCursor (IDC_ARROW);
WndClass.iBkColor = 0;
WndClass.WinProc = myButtonControlProc;
return RegisterWindowClass(&WndClass);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myButtonCleanUp 卸载控件
*/
/* ---------------------------------------------------------------------------*/
static void myButtonCleanUp (void)
{
UnregisterWindowClass(CTRL_NAME);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief paint 主要绘图函数
*
* @param hWnd
* @param hdc
*/
/* ---------------------------------------------------------------------------*/
static void paint(HWND hWnd,HDC hdc)
{
#define FILL_BMP_STRUCT(rc,img) rc.left, rc.top,img->bmWidth,img->bmHeight,img
RECT rc_bmp,*rc_text;
PCONTROL pCtrl;
pCtrl = Control (hWnd);
GetClientRect (hWnd, &rc_bmp);
rc_text = &rc_bmp;
MyButtonCtrlInfo* pInfo = (MyButtonCtrlInfo*)(pCtrl->dwAddData2);
if (!pCtrl->dwAddData2)
return;
if (pInfo->flag & MYBUTTON_TYPE_ONE_STATE) {
SetTextColor(hdc,pInfo->color_nor);
FillBoxWithBitmap(hdc,FILL_BMP_STRUCT(rc_bmp,pInfo->image_normal));
} else if (pInfo->flag & MYBUTTON_TYPE_TWO_STATE) {
if(pInfo->state == BUT_NORMAL) {
SetTextColor(hdc,pInfo->color_nor);
if (pInfo->flag & MYBUTTON_TYPE_PRESS_COLOR) {
SetBrushColor (hdc,0x333333);
FillBox (hdc, rc_bmp.left,rc_bmp.top,RECTW(rc_bmp),RECTH(rc_bmp));
} else if (pInfo->flag & MYBUTTON_TYPE_PRESS_COLOR) {
} else{
FillBoxWithBitmap(hdc, FILL_BMP_STRUCT(rc_bmp,pInfo->image_normal));
}
} else {
SetTextColor(hdc,pInfo->color_press);
if (pInfo->flag & MYBUTTON_TYPE_PRESS_COLOR) {
SetBrushColor (hdc,0x10B7F5);
FillBox (hdc, rc_bmp.left,rc_bmp.top,RECTW(rc_bmp),RECTH(rc_bmp));
} else if (pInfo->flag & MYBUTTON_TYPE_PRESS_COLOR) {
} else{
FillBoxWithBitmap(hdc, FILL_BMP_STRUCT(rc_bmp,pInfo->image_press));
}
}
} else if (pInfo->flag & MYBUTTON_TYPE_CHECKBOX){
if(pInfo->check == MYBUTTON_STATE_UNCHECK) {
SetTextColor(hdc,pInfo->color_press);
FillBoxWithBitmap(hdc, FILL_BMP_STRUCT(rc_bmp,pInfo->image_normal));
} else {
SetTextColor(hdc,pInfo->color_nor);
FillBoxWithBitmap(hdc, FILL_BMP_STRUCT(rc_bmp,pInfo->image_press));
}
}
if (!pInfo->text || (pInfo->flag & MYBUTTON_TYPE_TEXT_NULL))
return;
// SetTextColor(hdc,COLOR_lightwhite);
SetBkMode(hdc,BM_TRANSPARENT);
SelectFont (hdc, pInfo->font);
if (pInfo->flag & MYBUTTON_TYPE_TEXT_CENTER) {
if ((pInfo->flag & MYBUTTON_TYPE_PRESS_COLOR) == 0)
rc_text->bottom = rc_bmp.top + pInfo->image_normal->bmHeight;
DrawText (hdc,pInfo->text, -1, rc_text,
DT_CENTER | DT_VCENTER | DT_WORDBREAK | DT_SINGLELINE);
} else {
if ((pInfo->flag & MYBUTTON_TYPE_PRESS_COLOR) == 0)
rc_text->top = rc_bmp.top + pInfo->image_normal->bmHeight;
DrawText (hdc,pInfo->text, -1, rc_text,
DT_CENTER | DT_BOTTOM| DT_VCENTER | DT_WORDBREAK | DT_SINGLELINE);
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief myButtonControlProc 控件主回调函数
*
* @param hwnd
* @param message
* @param wParam
* @param lParam
*
* @returns
*/
/* ---------------------------------------------------------------------------*/
static int myButtonControlProc (HWND hwnd, int message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PCONTROL pCtrl;
DWORD dwStyle;
MyButtonCtrlInfo* pInfo;
pCtrl = Control (hwnd);
pInfo = (MyButtonCtrlInfo*)pCtrl->dwAddData2;
dwStyle = GetWindowStyle (hwnd);
switch (message) {
case MSG_CREATE:
{
MyButtonCtrlInfo* data = (MyButtonCtrlInfo*)pCtrl->dwAddData;
pInfo = (MyButtonCtrlInfo*) calloc (1, sizeof (MyButtonCtrlInfo));
if (pInfo == NULL)
return -1;
memset(pInfo,0,sizeof(MyButtonCtrlInfo));
pInfo->image_press = data->image_press;
pInfo->image_normal = data->image_normal;
pInfo->state = data->state;
pInfo->flag = data->flag;
pInfo->check = data->check;
pInfo->text = data->text;
pInfo->font = data->font;
pInfo->color_nor = data->color_nor;
pInfo->color_press = data->color_press;
pCtrl->dwAddData2 = (DWORD)pInfo;
return 0;
}
case MSG_DESTROY:
free(pInfo);
break;
case MSG_PAINT:
hdc = BeginPaint (hwnd);
paint(hwnd,hdc);
EndPaint (hwnd, hdc);
return 0;
case MSG_ENABLE:
if (wParam && (dwStyle & WS_DISABLED)) {
pCtrl->dwStyle &= ~WS_DISABLED;
pInfo->state = BUT_NORMAL;
} else if (!wParam && !(dwStyle & WS_DISABLED)) {
pCtrl->dwStyle |= WS_DISABLED;
pInfo->state = BUT_DISABLED;
} else {
return 0;
}
InvalidateRect (hwnd, NULL, FALSE);
return 0;
case MSG_LBUTTONDOWN:
if (GetCapture () == hwnd)
break;
if(pInfo->state == BUT_CLICK)
break; //已经是选中状态
SetCapture (hwnd);
pInfo->state = BUT_CLICK;
NotifyParent (hwnd, pCtrl->id, BN_PUSHED);
InvalidateRect (hwnd, NULL, TRUE);
break;
case MSG_LBUTTONUP:
{
int x, y;
if (GetCapture() != hwnd) {
if(pInfo->state!=BUT_NORMAL) {
pInfo->state = BUT_NORMAL;
InvalidateRect (hwnd, NULL, TRUE);
}
break;
}
ReleaseCapture ();
pInfo->state = BUT_NORMAL;
#ifdef X86
if (pInfo->flag == MYBUTTON_TYPE_CHECKBOX){
if (pInfo->check == MYBUTTON_STATE_CHECK)
pInfo->check = MYBUTTON_STATE_UNCHECK;
else
pInfo->check = MYBUTTON_STATE_CHECK;
}
NotifyParent (hwnd, pCtrl->id, BN_CLICKED);
#endif
InvalidateRect (hwnd, NULL, TRUE);
NotifyParent (hwnd, pCtrl->id, BN_UNPUSHED);
x = LOSWORD(lParam);
y = HISWORD(lParam);
//设置捕获后,坐标变成屏幕绝对值,需要转换为窗口坐标
if(wParam & KS_CAPTURED) {
ScreenToClient (GetParent (hwnd), &x, &y);
}
if (PtInRect ((PRECT) &(pCtrl->cl), x, y))
{
if (pInfo->flag == MYBUTTON_TYPE_CHECKBOX){
if (pInfo->check == MYBUTTON_STATE_CHECK)
pInfo->check = MYBUTTON_STATE_UNCHECK;
else
pInfo->check = MYBUTTON_STATE_CHECK;
}
NotifyParent (hwnd, pCtrl->id, BN_CLICKED);
InvalidateRect (hwnd, NULL, TRUE);
}
break;
}
default:
break;
}
return DefaultControlProc (hwnd, message, wParam, lParam);
}
/* ---------------------------------------------------------------------------*/
/**
* @brief bmpsMainButtonLoad 加载主界面图片
*
* @param controls
**/
/* ---------------------------------------------------------------------------*/
static void myButtonBmpsLoad(void *ctrls,char *path)
{
int i;
char image_path[128] = {0};
MyCtrlButton *controls = (MyCtrlButton *)ctrls;
for (i=0; controls->idc != 0; i++) {
if (controls->flag & MYBUTTON_TYPE_ONE_STATE) {
sprintf(image_path,"%s%s.png",path,controls->img_name);
bmpLoad(&controls->image_normal, image_path);
} else {
sprintf(image_path,"%sico_%s_nor.png",path,controls->img_name);
bmpLoad(&controls->image_normal, image_path);
sprintf(image_path,"%sico_%s_pre.png",path,controls->img_name);
bmpLoad(&controls->image_press, image_path);
}
controls++;
}
}
static void myButtonBmpsRelease(void *ctrls)
{
int i;
MyCtrlButton *controls = (MyCtrlButton *)ctrls;
for (i=0; controls->idc != 0; i++) {
bmpRelease(&controls->image_normal);
bmpRelease(&controls->image_press);
controls++;
}
}
/* ---------------------------------------------------------------------------*/
/**
* @brief createMyButton 创建单个皮肤按钮
*
* @param hWnd
* @param id
* @param x,y,w,h 坐标
* @param image_normal 正常图片
* @param image_press 按下图片
* @param display 是否显示 0不显示 1显示
* @param mode 是否为选择模式 0非选择 1选择
* @param notif_proc 回调函数
*/
/* ---------------------------------------------------------------------------*/
HWND createMyButton(HWND hWnd,MyCtrlButton *ctrl)
{
HWND hCtrl;
int ctrl_w = 0,ctrl_h = 0;
MyButtonCtrlInfo pInfo;
pInfo.image_normal = &ctrl->image_normal;
pInfo.image_press = &ctrl->image_press;
pInfo.state = BUT_NORMAL;
pInfo.check = MYBUTTON_STATE_UNCHECK;
pInfo.flag = ctrl->flag;
pInfo.text = ctrl->img_name;
pInfo.font = ctrl->font;
pInfo.color_nor = COLOR_lightwhite;
pInfo.color_press = COLOR_lightwhite;
if (ctrl->color_nor != 0)
pInfo.color_nor = ctrl->color_nor;
if (ctrl->color_press != 0)
pInfo.color_press = ctrl->color_press;
if ((pInfo.flag & MYBUTTON_TYPE_PRESS_COLOR)
|| (pInfo.flag & MYBUTTON_TYPE_PRESS_TRANSLATE)) {
ctrl_w = ctrl->w;
ctrl_h = ctrl->h;
} else {
ctrl_w = ctrl->image_normal.bmWidth;
ctrl_h = ctrl->image_normal.bmHeight;
if (ctrl->font) {
ctrl_h += pInfo.font->size + 30;
}
}
hCtrl = CreateWindowEx(CTRL_NAME,"",WS_VISIBLE|WS_CHILD,WS_EX_TRANSPARENT,
ctrl->idc,ctrl->x,ctrl->y,ctrl_w,ctrl_h, hWnd,(DWORD)&pInfo);
if(ctrl->notif_proc) {
SetNotificationCallback (hCtrl, ctrl->notif_proc);
}
return hCtrl;
}
void initMyButton(void)
{
my_button = (MyControls *)malloc(sizeof(MyControls));
my_button->regist = myButtonRegist;
my_button->unregist = myButtonCleanUp;
my_button->bmpsLoad = myButtonBmpsLoad;
my_button->bmpsRelease = myButtonBmpsRelease;
}
<file_sep>/src/app/state_machine.h
/*
* =============================================================================
*
* Filename: stateMachine.h
*
* Description: 状态机处理
*
* Version: 1.0
* Created: 2016-11-25 14:49:31
* Revision: 1.0
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _STATE_MACHINE_H
#define _STATE_MACHINE_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define DBG_MACHINE 1
typedef struct _StateTableDebug {
char **ev;
char **st;
char **todo;
}StateTableDebug;
typedef struct _StateTable {
int msg; // 事件消息
int cur_state; // 当前状态
int next_state; // 下一状态
int run; // 执行处理
}StateTable;
struct _StMachinePriv;
typedef struct _StMachine {
struct _StMachinePriv *priv;
int id;
void *(*initPara)(struct _StMachine *,int size);
int (*getCurrentstate)(struct _StMachine *);
void (*setCurrentstate)(struct _StMachine *,int state);
int (*getCurRun)(struct _StMachine *);
/* ---------------------------------------------------------------------------*/
/**
* @brief 发送异步消息
*
* @param
* @param msg 消息值
* @param data 附加数据,需要用initPara初始化
*/
/* ---------------------------------------------------------------------------*/
void (*msgPost)(struct _StMachine *,int msg,void *data);
/* ---------------------------------------------------------------------------*/
/**
* @brief 发送同步消息
*
* @param
* @param msg 消息值
* @param data 附加数据,直接传入参数,无需初始化
*
* @returns -1为未找到当前消息对应执行动作,其他为执行动作返回值
*/
/* ---------------------------------------------------------------------------*/
int (*msgPostSync)(struct _StMachine *,int msg,void *data);
int (*handle)(struct _StMachine *,int result,void *data,void *arg);
void (*destroy)(struct _StMachine **);
}StMachine;
StMachine* stateMachineCreate(int init_state,
StateTable *state_table,
int num,
int id,
int (*handle)(StMachine *,int result,void *data,void *arg),
void *arg,
StateTableDebug *st_debug);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/video/h264_enc_dec/h264_split.c
/*
* =============================================================================
*
* Filename: h264_split.c
*
* Description: h264 sps pps分隔
*
* Version: virsion
* Created: 2019-08-15 09:01:47
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdint.h>
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
// Copy from ffmpeg.
static const uint8_t *find_startcode_internal(const uint8_t *p,
const uint8_t *end)
{
const uint8_t *a = p + 4 - ((intptr_t)p & 3);
for (end -= 3; p < a && p < end; p++) {
if (p[0] == 0 && p[1] == 0 && p[2] == 1)
return p;
}
for (end -= 3; p < end; p += 4) {
uint32_t x = *(const uint32_t *)p;
// if ((x - 0x01000100) & (~x) & 0x80008000) // little endian
// if ((x - 0x00010001) & (~x) & 0x00800080) // big endian
if ((x - 0x01010101) & (~x) & 0x80808080) { // generic
if (p[1] == 0) {
if (p[0] == 0 && p[2] == 1)
return p;
if (p[2] == 0 && p[3] == 1)
return p + 1;
}
if (p[3] == 0) {
if (p[2] == 0 && p[4] == 1)
return p + 2;
if (p[4] == 0 && p[5] == 1)
return p + 3;
}
}
}
for (end += 3; p < end; p++) {
if (p[0] == 0 && p[1] == 0 && p[2] == 1)
return p;
}
return end + 3;
}
static const uint8_t *find_h264_startcode(const uint8_t *p, const uint8_t *end)
{
const uint8_t *out = find_startcode_internal(p, end);
if (p < out && out < end && !out[-1])
out--;
return out;
}
int split_h264_separate(const uint8_t *buffer, size_t length,int *sps_length,int *pps_length)
{
const uint8_t *p = buffer;
const uint8_t *end = p + length;
const uint8_t *nal_start = NULL, *nal_end = NULL;
nal_start = find_h264_startcode(p, end);
// 00 00 01 or 00 00 00 01
size_t start_len = (nal_start[2] == 1 ? 3 : 4);
uint8_t nal_type = 1;
for (;;) {
if (nal_start == end)
break;
nal_start += start_len;
nal_end = find_h264_startcode(nal_start, end);
size_t size = nal_end - nal_start + start_len;
nal_type = (*nal_start) & 0x1F;
if (nal_type == 7) {
*sps_length = size;
} else if (nal_type == 8) {
*pps_length = size;
}
// printf("nal_type:%d,length:%ld,size:%ld\n",nal_type,length,size );
nal_start = nal_end;
}
return nal_type;
}
<file_sep>/src/gui/commongdi.h
/*
* =====================================================================================
*
* Filename: common.h
*
* Description: 公共自定义画图函数
*
* Version: 1.0
* Created: 2015-11-11 11:50:08
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =====================================================================================
*/
#ifndef _MY_COMMON_H
#define _MY_COMMON_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <minigui/common.h>
#include <minigui/minigui.h>
#include <minigui/gdi.h>
#include <minigui/window.h>
#include <minigui/control.h>
#ifndef X86
#include <minigui/rkfb.h>
#endif
#include <stdint.h>
#include "form_idcs.h"
#define BMP_RES_PATH "res/image/"
#define SCR_WIDTH 1024 /*LCD Width */
#define SCR_HEIGHT 600 /*LCD Height */
typedef struct _BmpLocation {
BITMAP *bmp;
char *location;
}BmpLocation;
typedef struct _FontLocation {
PLOGFONT *font;
int size;
int first_type;
}FontLocation;
#define STATIC_LB(x,y,w,h,id,caption,font,color) \
{"static",WS_CHILD|WS_VISIBLE|SS_CENTER,x,y,w,h,id,caption,0,WS_EX_TRANSPARENT,NULL,NULL,font,color}
#define STATIC_LB_LEFT(x,y,w,h,id,caption,font,color) \
{"static",WS_CHILD|WS_VISIBLE|SS_LEFT,x,y,w,h,id,caption,0,WS_EX_TRANSPARENT,NULL,NULL,font,color}
#define STATIC_IMAGE(x,y,w,h,id,dwAddData) \
{"static",WS_CHILD|WS_VISIBLE|SS_BITMAP|SS_CENTERIMAGE|SS_REALSIZEIMAGE,x,y,w,h,id,"",dwAddData,WS_EX_TRANSPARENT,NULL,NULL,NULL,0}
#define SCROLLVIEW(x,y,w,h,id) \
{"scrollview",WS_CHILD|WS_VISIBLE,x,y,w,h,id,"",0,WS_EX_TRANSPARENT,NULL,NULL,NULL,0}
#define ICONVIEW(x,y,w,h,id) \
{CTRL_ICONVIEW,WS_CHILD|WS_VISIBLE,x,y,w,h,id,"",0,WS_EX_NONE,NULL,NULL,NULL,0}
#define EDIT(x,y,w,h,id,caption,font,color) \
{CTRL_SLEDIT,WS_CHILD|WS_VISIBLE|ES_CENTER,\
x,y,w,h,id,caption,0,WS_EX_TRANSPARENT,NULL,NULL,font,color}
void drawBackground(HWND hWnd, HDC hdc, const RECT* pClipRect,BITMAP *Image,int color);
void drawWhiteFrame(HWND hWnd, HDC hdc, const RECT* pClipRect,int Left,int Top,int Width,int Height);
void drawRectangle (HDC hdc, int x0, int y0, int x1, int y1, int color);
void wndEraseBackground(HWND hWnd,HDC hdc, const RECT* pClipRect,BITMAP *pImage,int Left,int Top,int Width,int Height);
void getPartFromBmp(const BITMAP *bmp,BITMAP *DstBitmap,int Left,int Top,int Width,int Height);
void myFillBox(HDC hdc, RECT *rc, int color);
void translateIconPart(HDC hdc,int x,int y,int w,int h,BITMAP *FgBmp,int LineIconCnt,int IconIdx,int t,
BOOL Translate);
void bmpLoad(BITMAP *bmp,char *path);
void bmpsLoad(BmpLocation *bmp);
void bmpRelease(BITMAP *bmp);
void bmpsRelease(BmpLocation *bmp);
void fontsLoad(FontLocation *font);
int myMoveWindow(HWND ctrl, int x,int y);
extern PLOGFONT font36;
extern PLOGFONT font22;
extern PLOGFONT font20;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/hal/hal_battery.c
/*
* =============================================================================
*
* Filename: hal_battery.c
*
* Description: 硬件层 看门狗接口
*
* Version: 1.0
* Created: 2018-12-12 15:51:59
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include "hal_battery.h"
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define SAVE_ELE 5
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
int halBatteryGetEle(void)
{
#ifdef X86
return 10;
#else
char data[4] = {0};
int disp_value = 0;
int fd = open("/sys/class/power_supply/battery/capacity",O_RDONLY);
if (fd != -1) {
read(fd,data,sizeof(data));
close(fd);
}
int real_value = atoi(data);
// 为保持有最低安全电量,当实际电量低于SAVE_ELE时,显示设置为0
if (real_value <= SAVE_ELE) {
disp_value = 0;
} else {
disp_value = 100 * (real_value - SAVE_ELE)/ (100 - SAVE_ELE) ;
}
// printf("re:%d,dis:%d\n", real_value,disp_value);
return disp_value;
#endif
}
int halBatteryGetState(void)
{
#ifdef X86
return BATTERY_NORMAL;
#else
char data[16] = {0};
int fd = open("/sys/class/power_supply/battery/status",O_RDONLY);
if (fd != -1) {
read(fd,data,sizeof(data));
close(fd);
}
// printf("state:%s\n", data);
if (strncmp(data,"Charging",strlen("Charging")) == 0) {
return BATTERY_CHARGING;
} else {
return BATTERY_NORMAL;
}
#endif
}
<file_sep>/src/drivers/timer.h
/*
* =============================================================================
*
* Filename: Timer.h
*
* Description: 定时器20ms
*
* Version: v1.0
* Created: 2016-08-08 18:33:18
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _TIMER_H
#define _TIMER_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define TIMER_1S 1000
struct _TimerPriv;
typedef struct _Timer {
struct _TimerPriv *priv;
// 需要调用handle在已有定时器中运行
void (*start)(struct _Timer *);
void (*stop)(struct _Timer *);
void (*destroy)(struct _Timer *);
int (*handle)(struct _Timer *);
void (*resetTick)(struct _Timer *);
unsigned int (*getSystemTick)(void);
int (*isStop)(struct _Timer *);
// real timer 系统定时器,根据不同系统进行定制
void (*realTimerCreate)(struct _Timer *, double times, void (*function)(int ,int ));
void (*realTimerDelete)(struct _Timer *);
} Timer;
Timer * timerCreate(int speed,void (*function)(void *),void *arg);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/app/my_face.h
/*
* =============================================================================
*
* Filename: my_face.h
*
* Description: 人脸识别算法接口
*
* Version: 1.0
* Created: 2019-06-17 15:26:22
* Revision: none
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
#ifndef _MY_FACE_H
#define _MY_FACE_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define IAMGE_MAX_W 1280
#define IAMGE_MAX_H 720
#define IMAGE_MAX_DATA (IAMGE_MAX_W * IAMGE_MAX_H * 3 / 2 )
typedef struct _MyFaceData {
char user_id[32];
char nick_name[128];
char url[256];
int sex;//0: female, 1: male, -1: invalid value
int age;//>=0, -1: invalid value
}MyFaceData;
typedef struct _MyFaceRegistData {
unsigned char *image_buff;
int w,h;
char *id;
char *nick_name;
char *url;
}MyFaceRegistData;
typedef struct _MyFaceRecognizer {
unsigned char *image_buff;
int w,h;
int age;
int sex;
}MyFaceRecognizer;
typedef struct _MyFace{
/* ---------------------------------------------------------------------------*/
/**
* @brief int 返回0为开启人脸识别,返回1初始化成功,-1初始化失败
*
* @param
*/
/* ---------------------------------------------------------------------------*/
int (*init)(void);
int (*deleteOne)(char *id);
int (*regist)(MyFaceRegistData *data);
int (*recognizer)(char *image_buff,int w,int h); // 0未开启人脸识别 1开启人脸识别
int (*recognizerOnce)(MyFaceRecognizer *data);
void (*uninit)(void);
const char * (*getVersion)(void);
const char * (*getDeviceKey)(void);
}MyFace;
extern MyFace *my_face;
void myFaceInit(void);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
<file_sep>/src/drivers/queue.c
/*
* =============================================================================
*
* Filename: Queue.c
*
* Description: 队列
*
* Version: 1.0
* Created: 2016-08-16 09:08:15
* Revision: linux 需要内核配置支持
*
* Author: xubin
* Company: Taichuan
*
* =============================================================================
*/
/* ---------------------------------------------------------------------------*
* include head files
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* extern variables declare
*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <pthread.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <semaphore.h>
#include <mqueue.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "queue.h"
/* ---------------------------------------------------------------------------*
* internal functions declare
*----------------------------------------------------------------------------*/
/* ---------------------------------------------------------------------------*
* macro define
*----------------------------------------------------------------------------*/
#define QUEUE_LOCK() pthread_mutex_lock(&This->priv->mutex)
#define QUEUE_UNLOCK() pthread_mutex_unlock(&This->priv->mutex)
typedef struct _QueuePriv {
char name[32];
QueueType type;
unsigned int size;
int queue;
void *buf[MAX_COMMAND_QUEUE_SIZE];
sem_t *sem; //信号量
int current_length; // 当前fifo已存储的长度
int index_post; //索引
int index_get; //索引
pthread_mutex_t mutex; //队列控制互斥信号
pthread_mutexattr_t mutexattr2;
}QueuePriv;
/* ---------------------------------------------------------------------------*
* variables define
*----------------------------------------------------------------------------*/
/* ----------------------------------------------------------------*/
/**
* 线程操作时信号量处理
* @brief my_sem_post_get
* @brief my_sem_wait_get
*
* @param This
*/
/* ----------------------------------------------------------------*/
static void semPost(Queue * This)
{
sem_post(This->priv->sem);
}
static void semWait(Queue * This)
{
sem_wait(This->priv->sem);
}
//----------------------------------------------------------------------------
static void destroy(Queue * This)
{
if (This->priv->type == QUEUE_NONBLOCK) {
mq_close(This->priv->queue);
mq_unlink(This->priv->name);
} else {
unsigned int i;
sem_destroy(This->priv->sem);
for(i=0;i<MAX_COMMAND_QUEUE_SIZE;i++) {
if (This->priv->buf[i]) {
free(This->priv->buf[i]);
This->priv->buf[i] = NULL;
}
}
free(This->priv->sem);
pthread_mutex_destroy (&This->priv->mutex);
}
free(This->priv);
free(This);
}
//----------------------------------------------------------------------------
static void queuePost(Queue * This,void *data)
{
if (This->priv->type == QUEUE_NONBLOCK) {
if (msgsnd(This->priv->queue, (const char*)data, This->priv->size, IPC_NOWAIT))
fprintf(stderr, "mq_send failed: %s\n", strerror(errno));
} else {
if (This->priv->current_length >= MAX_COMMAND_QUEUE_SIZE) {
printf("fifo full!!%s\n",This->priv->name);
return;
}
QUEUE_LOCK();
if (This->priv->index_post >= MAX_COMMAND_QUEUE_SIZE) {
This->priv->index_post = 0;
}
This->priv->buf[This->priv->index_post] = (void *) calloc (1,This->priv->size);
if (This->priv->buf[This->priv->index_post] == NULL) {
printf("[%s] can't calloc memory\n", __func__);
return;
}
if (This->priv->size)
memcpy(This->priv->buf[This->priv->index_post],data,This->priv->size);
This->priv->index_post++;
This->priv->current_length++;
QUEUE_UNLOCK();
semPost(This);
}
}
static int queueGet(Queue *This,void *data)
{
if (This->priv->type == QUEUE_NONBLOCK) {
return msgrcv(This->priv->queue, (void *)data, This->priv->size, 0,IPC_NOWAIT);
// return mq_receive(This->priv->queue, (char*)data, This->priv->size, 0);
}
semWait(This);
if (This->priv->current_length == 0) {
printf("fifo empty!!\n");
return 0;
}
QUEUE_LOCK();
if (This->priv->index_get >= MAX_COMMAND_QUEUE_SIZE) {
This->priv->index_get = 0;
}
if (This->priv->size)
memcpy(data,This->priv->buf[This->priv->index_get],This->priv->size);
free(This->priv->buf[This->priv->index_get]);
This->priv->buf[This->priv->index_get] = NULL;
This->priv->index_get++;
This->priv->current_length--;
QUEUE_UNLOCK();
return 0;
}
/* ---------------------------------------------------------------------------*/
/**
* @brief queueSetDataSize 重新设置队列数据大小
*
* @param This
* @param size
*/
/* ---------------------------------------------------------------------------*/
static void queueSetDataSize(Queue *This,int size)
{
This->priv->size = size;
}
/* ----------------------------------------------------------------*/
/**
* @brief queueCreate 创建对列
*
* @param Size 参数大小
*
* @returns
*/
/* ----------------------------------------------------------------*/
Queue * queueCreate(const char *queue_name,QueueType type,unsigned int Size)
{
Queue * This = (Queue *)calloc(1,sizeof(Queue));
if(This == NULL) {
printf("fifo calloc failed !!!\n");
return NULL;
}
This->priv = (QueuePriv *)calloc(1,sizeof(QueuePriv));
if(This == NULL) {
printf("fifo priv calloc failed !!!\n");
free(This);
return NULL;
}
This->priv->type = type;
if (This->priv->type == QUEUE_NONBLOCK) {
// struct mq_attr attr;
// attr.mq_flags = 0;
// attr.mq_maxmsg = MAX_COMMAND_QUEUE_SIZE;
// attr.mq_msgsize = Size;
strcpy(This->priv->name,queue_name);
This->priv->queue = msgget((key_t)1234,0666|IPC_CREAT);
if (This->priv->queue < 0)
fprintf(stderr, "mq_create failed: %s\n", strerror(errno));
} else {
//设置互斥锁属性
pthread_mutexattr_init(&This->priv->mutexattr2);
/* Set the mutex as a recursive mutex */
pthread_mutexattr_settype(&This->priv->mutexattr2,
PTHREAD_MUTEX_RECURSIVE_NP);
// PTHREAD_MUTEX_RECURSIVE_NP);
/* create the mutex with the attributes set */
pthread_mutex_init(&This->priv->mutex, &This->priv->mutexattr2);
/* destroy the attribute */
pthread_mutexattr_destroy(&This->priv->mutexattr2);
This->priv->sem = (sem_t *) calloc(1,sizeof(sem_t));
sem_init (This->priv->sem, 0,0); //读信号量初始化为0
This->priv->current_length = 0;
This->priv->index_get = 0;
This->priv->index_post = 0;
}
This->priv->size = Size;
This->post = queuePost;
This->get = queueGet;
This->destroy = destroy;
return This;
}
<file_sep>/src/app/video/process/display_process.cpp
#include "display_process.h"
#include "thread_helper.h"
#include "h264_enc_dec/mpi_dec_api.h"
#include "jpeg_enc_dec.h"
#include "libyuv.h"
#define CAMMER_TICK_NUM 5
static FILE *fp = NULL;
static int cammer_tick = CAMMER_TICK_NUM; // 摄像头正常连接计数,当计数为0,判断摄像头接线异常
static bool cammer_check_thread = false;
int NV12Scale(unsigned char *psrc_buf, int psrc_w, int psrc_h, unsigned char **pdst_buf, int pdst_w, int pdst_h);
static void writePicture(unsigned char *data,int w,int h)
{
if (fp == NULL)
return;
unsigned char *jpeg_buf = NULL;
int size = 0;
yuv420spToJpeg(data,w,h,&jpeg_buf,&size);
if (jpeg_buf) {
fwrite(jpeg_buf,1,size,fp);
fflush(fp);
fclose(fp);
free(jpeg_buf);
}
fp = NULL;
}
static void* threadCheckCammer(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
cammer_check_thread = true;
DisplayProcess *process = (DisplayProcess *)arg;
while (1) {
// printf("dec:%d,tick:%d\n",process->start_dec(),cammer_tick );
if (process->start_dec() == false && cammer_tick > 0) {
if (--cammer_tick == 0) {
process->setCammerState(0);
break;
}
}
sleep(1);
}
cammer_check_thread = false;
return NULL;
}
DisplayProcess::DisplayProcess()
: StreamPUBase("DisplayProcess", true, true)
{
rga_fd = rk_rga_open();
if (rga_fd < 0)
printf("rk_rga_open failed\n");
cammer_state_ = 1;
cammer_tick = CAMMER_TICK_NUM;
myH264DecInit();
if (cammer_check_thread == false)
createThread(threadCheckCammer,this);
}
DisplayProcess::~DisplayProcess()
{
rk_rga_close(rga_fd);
cammer_state_ = 0;
}
bool DisplayProcess::processFrame(std::shared_ptr<BufferBase> inBuf,
std::shared_ptr<BufferBase> outBuf)
{
cammer_tick = CAMMER_TICK_NUM;
int src_w = inBuf->getWidth();
int src_h = inBuf->getHeight();
int src_fd = (int)(inBuf->getFd());
int vir_w = src_w;
int vir_h = src_h;
int src_fmt = RGA_FORMAT_YCBCR_420_SP;
int screen_width = 0, screen_height = 0;
struct win* video_win = rk_fb_getvideowin();
int out_device = rk_fb_get_out_device(&screen_width, &screen_height);
int dst_fd = video_win->video_ion.fd;
int dst_fmt = RGA_FORMAT_YCBCR_420_SP;
int dst_w = screen_width;
int dst_h = screen_height;
int rotate_angle = (out_device == OUT_DEVICE_HDMI ? 0 : 0);
int ret = rk_rga_ionfd_to_ionfd_rotate(rga_fd,
src_fd, src_w, src_h, src_fmt, vir_w, vir_h,
dst_fd, dst_w, dst_h, dst_fmt,
rotate_angle);
if (ret) {
printf("rk_rga_ionfd_to_ionfd_rotate failed\n");
return false;
}
writePicture((unsigned char *)inBuf->getVirtAddr(),1280,720);
if (rk_fb_video_disp(video_win) < -1){
printf("rk_fb_video_disp failed\n");
}
return true;
}
void DisplayProcess::setVideoBlack()
{
int screen_width = 0, screen_height = 0;
struct win* video_win = rk_fb_getvideowin();
int out_device = rk_fb_get_out_device(&screen_width, &screen_height);
int screen_size = screen_width*screen_height;
if (video_win->buffer) {
memset(video_win->buffer,0,screen_size);
memset(video_win->buffer + screen_size,0x80,screen_size/2);
}
if (rk_fb_video_disp(video_win) < -1){
printf("rk_fb_video_disp failed\n");
}
cammer_tick = 0;
}
void DisplayProcess::showLocalVideo(void)
{
start_dec_ = false;
}
static void* threadH264Dec(void *arg)
{
prctl(PR_SET_NAME, __func__, 0, 0, 0);
DisplayProcess *process = (DisplayProcess *)arg;
struct win* video_win = rk_fb_getvideowin();
unsigned char data_in[1024*200];
unsigned char data_out[1280*720*3/2];
int out_w = 0,out_h = 0;
int screen_width = 0, screen_height = 0;
int out_device = rk_fb_get_out_device(&screen_width, &screen_height);
#ifdef USE_UDPTALK
if (my_h264dec)
my_h264dec->init(my_h264dec,process->getWidth(),process->getHeight());
#endif
while (process->start_dec() == true) {
int size_in = 0;
int size_out = 0;
memset(data_in,0,sizeof(data_in));
memset(data_out,0,sizeof(data_out));
if (process->decCallback())
process->decCallback()(data_in,&size_in);
unsigned char *nv12_scale_data = NULL;
if (size_in > 0) {
if (my_h264dec)
size_out = my_h264dec->decode(my_h264dec,data_in,size_in,data_out,&out_w,&out_h);
if (out_w != 0 && out_h != 0 && size_out > 0) {
int disp_width = out_w * screen_height / out_h;
if (disp_width < 600)
disp_width = 600;
else if (disp_width > 1024)
disp_width = 1024;
NV12Scale(data_out, out_w, out_h, &nv12_scale_data, disp_width, screen_height);
int y_size = disp_width*screen_height;
int i;
// Y
// 居中显示,图像起点
int disp_start_x = (screen_width - disp_width) / 2;
int data_index = 0;
if (video_win->buffer) {
for (i = 0; i < screen_height; ++i) {
memset(video_win->buffer + i*screen_width,0,disp_start_x);
memcpy(video_win->buffer + i*screen_width + disp_start_x,&nv12_scale_data[disp_width * data_index++],disp_width);
memset(video_win->buffer + i*screen_width + disp_start_x + disp_width,0,disp_start_x);
}
}
// uv
int k ;
if (video_win->buffer) {
for (k = 0; k < screen_height / 2; ++k,++i) {
memset(video_win->buffer + i*screen_width,0x80,disp_start_x);
memcpy(video_win->buffer + i*screen_width + disp_start_x,&nv12_scale_data[disp_width * data_index++],disp_width);
memset(video_win->buffer + i*screen_width + disp_start_x + disp_width,0x80,disp_start_x);
}
}
writePicture(nv12_scale_data,disp_width,screen_height);
if (rk_fb_video_disp(video_win) < -1){
printf("rk_fb_video_disp failed\n");
}
}
}
if (nv12_scale_data)
free(nv12_scale_data);
usleep(10000);
}
if (my_h264dec)
my_h264dec->unInit(my_h264dec);
printf("%s(),%d\n", __func__,__LINE__);
return NULL;
}
void DisplayProcess::showPeerVideo(int w,int h,DecCallbackFunc decCallback)
{
width_ = w;
height_ = h;
decCallback_ = decCallback;
start_dec_ = true;
setVideoBlack();
createThread(threadH264Dec,this);
}
void DisplayProcess::capture(char *file_name)
{
while (fp != NULL) {
usleep(10000);
}
if (fp == NULL)
fp = fopen(file_name,"wb");
}
|
8648494f74ae52bf53f242dcc8922cfca37fd645
|
[
"C",
"CMake",
"C++",
"Shell"
] | 211
|
C
|
bill611/cat_eye
|
356a3bb1d39fd80cf26e57897f9471cdbf865c3f
|
bb8504fa18be92b4b9a838fbcff755c8250fed33
|
refs/heads/master
|
<file_sep>import time
from urllib.request import Request
import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from app import init_data
from app.api.api import api_router
from app.core import config
from app.database.session import database
app = FastAPI(title='Simple Workout Tracker API')
# CORS
origins = []
# Set all CORS enabled origins
if config.BACKEND_CORS_ORIGINS:
origins_raw = config.BACKEND_CORS_ORIGINS.split(",")
for origin in origins_raw:
use_origin = origin.strip()
origins.append(use_origin)
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
),
app.include_router(api_router, prefix="/api")
@app.on_event("startup")
async def startup():
await database.connect()
await init_data.init()
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
if __name__ == "__main__":
uvicorn.run('app.main:app', host=config.SERVER_HOST, port=config.SERVER_PORT)
<file_sep>"""add username to User model
Revision ID: 33251cd99f28
Revises: <KEY>
Create Date: 2020-03-27 15:59:55.450039
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '33251cd99f28'
down_revision = '5277021a51cf'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('user', sa.Column('username', sa.String(), nullable=True))
op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_user_username'), table_name='user')
op.drop_column('user', 'username')
# ### end Alembic commands ###
<file_sep>from datetime import datetime
from asyncpg import Record
from fastapi.encoders import jsonable_encoder
from app.core.security import verify_password, get_password_hash
from app.crud.base import CRUDBase
from app.database.session import database
from app.models.user import User
from app.schemas.user import UserCreate, UserUpdate
class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]):
async def get_by_email(self, email: str) -> Record:
query = self.model.__table__.select().where(email.lower() == self.model.email)
return await database.fetch_one(query=query)
async def get_by_username(self, username: str) -> Record:
query = self.model.__table__.select().where(username == self.model.username)
return await database.fetch_one(query=query)
async def create(self, obj_in: UserCreate) -> int:
query = self.model.__table__.insert().values(email=obj_in.email.lower(),
username=obj_in.username,
hashed_password=get_password_hash(obj_in.password),
first_name=obj_in.first_name,
last_name=obj_in.last_name,
date_created=datetime.utcnow(),
is_email_verified=obj_in.is_email_verified,
is_superuser=obj_in.is_superuser,
is_active=obj_in.is_active).returning(self.model.id)
return await database.execute(query=query)
async def update(self, id: int, obj_in: UserUpdate) -> int:
obj_in_data = jsonable_encoder(obj_in)
if 'password' in obj_in_data.keys() and obj_in_data['password']:
obj_in_data['hashed_password'] = get_password_hash(obj_in_data.pop('password'))
elif 'hashed_password' in obj_in_data:
obj_in_data['hashed_password'] = None
query = (self.model.__table__.update().where(id == self.model.id).values(
{k: v for k, v in obj_in_data.items() if v})).returning(
self.model.id)
return await database.execute(query=query)
async def authenticate(
self, username: str, password: str
):
record = await self.get_by_username(username=username)
if not record:
record = await self.get_by_email(email=username)
if not record:
return None
user = User(**record)
if not verify_password(password, user.hashed_password):
return None
return user
user = CRUDUser(User)
<file_sep>from app import crud
from app.core import config
from app.schemas.user import SuperUserCreate
# make sure all SQL Alchemy models are imported before initializing DB
# otherwise, SQL Alchemy might fail to initialize relationships properly
from app.database import base
async def init_database():
user = await crud.user.get_by_username(username=config.SUPERUSER)
if not user:
user_in = SuperUserCreate(
username=config.SUPERUSER,
password=<PASSWORD>,
email='<EMAIL>',
is_superuser=True
)
await crud.user.create(obj_in=user_in)
<file_sep>import logging
from app.database.init_database import init_database
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
async def init():
logger.info("Creating initial data")
await init_database()
logger.info("Initial data created")
<file_sep>import databases
from app.core import config
database = databases.Database(url=config.DATABASE_URL, ssl='allow')
<file_sep>from typing import List, Generic, TypeVar, Type
from asyncpg import Record
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from app.database.base import Base
from app.database.session import database
ModelType = TypeVar("ModelType", bound=Base)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
def __init__(self, model: Type[ModelType]):
"""
CRUD object with default methods to Create, Read, Update, Delete (CRUD).
**Parameters**
* `model`: A SQLAlchemy model class
* `schema`: A Pydantic model (schema) class
"""
self.model = model
async def get(self, id: int) -> Record:
"""
Return single record from given object ID.
:param id: Database object id.
:return: asyncpg Record object containing data.
"""
query = self.model.__table__.select().where(id == self.model.id)
return await database.fetch_one(query=query)
async def get_multi(self, skip=0, limit=100) -> List[Record]:
"""
Return list of desired objects.
:param skip: How many of first objects to skip in the result.
:param limit: Max number of objects to get from query.
:return: List of asyncpg Record objects containing data.
"""
query = self.model.__table__.select().offset(skip).limit(limit)
return await database.fetch_all(query=query)
async def create(self, obj_in: CreateSchemaType) -> int:
"""
Create object in database.
:param obj_in: Class inheriting from pydantic BaseModel with attributes needed for object creation.
:return: id of created object.
"""
obj_in_data = jsonable_encoder(obj_in)
query = self.model.__table__.insert().values(**obj_in_data)
return await database.execute(query=query)
async def update(self, id: int, obj_in: UpdateSchemaType) -> int:
"""
Update object with given id.
:param id: id of updated object in database.
:param obj_in: Class inheriting from pydantic BaseModel with attributes needed for object update.
:return: id of updated object in database.
"""
obj_in_data = jsonable_encoder(obj_in)
db_obj = self.model(**obj_in_data)
query = (
self.model.__table__.update().where(id == self.model.id).values(**db_obj).returning(self.model.id)
)
return await database.execute(query=query)
async def remove(self, id: int) -> int:
"""
Remove object with given id.
:param id: id of object in database.
:return: id of object in database.
"""
query = self.model.__table__.delete().where(id == self.model.id).returning(self.model.id)
return await database.execute(query=query)
async def remove_all(self) -> int:
"""
Remove all rows from table.
:param id: id of object in database.
:return: id of object in database.
"""
query = self.model.__table__.delete()
return await database.execute(query=query)
<file_sep>import jwt
from fastapi import HTTPException, Security
from fastapi.security import OAuth2PasswordBearer
from jwt import PyJWTError
from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN, HTTP_404_NOT_FOUND
from app import crud
from app.core import config
from app.core.token import ALGORITHM
from app.schemas.user import User
from app.schemas.token import TokenPayload
reusable_oauth2 = OAuth2PasswordBearer(tokenUrl="/api/login/access-token")
async def get_current_user(token: str = Security(reusable_oauth2)):
try:
payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
token_data = TokenPayload(**payload)
except PyJWTError:
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
user = await crud.user.get(id=token_data.user_id)
if not user:
raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="User not found")
return User(**user)
def get_current_active_user(current_user: User = Security(get_current_user)):
if not current_user.is_active:
raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Inactive user")
return current_user
def get_current_active_superuser(current_user: User = Security(get_current_user)):
if not current_user.is_superuser:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="The user doesn't have enough privileges"
)
return current_user
<file_sep>from typing import List
from starlette.status import HTTP_409_CONFLICT
from app import crud
from fastapi import APIRouter, HTTPException
from app.schemas.exercise import Exercise, ExerciseCreate
router = APIRouter()
@router.get("", response_model=List[Exercise])
async def read_exercises(
skip: int = 0,
limit: int = 100,
):
"""
Retrieve exercises.
"""
return await crud.exercise.get_multi(skip, limit)
@router.post("", response_model=Exercise)
async def create_exercise(
exercise_in: ExerciseCreate
):
"""
Create new exercise.
"""
exercise = await crud.exercise.get_by_name(name=exercise_in.name)
if exercise:
raise HTTPException(
status_code=HTTP_409_CONFLICT,
detail="The exercise with this name already exists in the system.",
)
exercise_id = await crud.exercise.create(obj_in=exercise_in)
return await crud.exercise.get(exercise_id)
<file_sep>from asyncpg import Record
from app.crud.base import CRUDBase
from app.database.session import database
from app.models.exercise import Exercise
from app.schemas.exercise import ExerciseCreate, ExerciseUpdate
class CRUDExercise(CRUDBase[Exercise, ExerciseCreate, ExerciseUpdate]):
async def get_by_name(self, name: str) -> Record:
query = self.model.__table__.select().where(name == self.model.name)
return await database.fetch_one(query=query)
exercise = CRUDExercise(Exercise)
<file_sep>pytest
emails
databases
asyncpg
alembic==1.4.2
bcrypt==3.1.7
cffi==1.14.0
click==7.1.1
dnspython==1.16.0
email-validator==1.0.5
fastapi==0.52.0
FastAPI-SQLAlchemy==0.1.3
h11==0.9.0
idna==2.9
Mako==1.1.2
MarkupSafe==1.1.1
passlib==1.7.2
psycopg2==2.8.4
pycparser==2.20
pydantic==1.4
PyJWT==1.7.1
python-dateutil==2.8.1
python-dotenv==0.12.0
python-editor==1.0.4
python-multipart==0.0.5
six==1.14.0
SQLAlchemy==1.3.15
starlette==0.13.2
uvicorn==0.11.3
websockets==8.1
<file_sep>from fastapi import APIRouter
from app.api import user, login, test, exercise
api_router = APIRouter()
api_router.include_router(login.router, tags=["login"])
api_router.include_router(exercise.router, prefix="/exercises", tags=["exercises"])
api_router.include_router(user.router, prefix="/users", tags=["users"])
api_router.include_router(test.router, prefix="/tests", tags=["tests"])
<file_sep>"""test_imports
Revision ID: 5277021a51cf
Revises: <KEY>
Create Date: 2020-03-26 12:27:27.142476
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
<file_sep># Simple workout tracker API
Asynchronous API for workout tracker application.
Created with FastAPI and PostgreSQL database.
## Installation
Clone repo.
Use the package manager [pip](https://pip.pypa.io/en/stable/) to install all dependencies from requirements file.
```bash
pip install -r requirements.txt
```
## Environmental variables
Before running the server, `.env` file with input variables needs to be created in project root directory, like so:
```text
VAR1_NAME=VAR1_VALUE
VAR2_NAME=VAR2_VALUE
...
```
Variables list:
* `DATABASE_URL`: URL of PostgreSQL database. Syntax:
```text
postgresql://username:password:@server_address/database_name
```
* `SECRET_KEY`: 256-bit unique hex key used for password encryption.
* `SUPERUSER`: Superuser login.
* `SUPERUSER_PASSWORD`: <PASSWORD>user <PASSWORD>.
Include this only if running server by executing `main.py`:
* `SERVER_HOST`: Server address. Use `0.0.0.0` to make application available on local network.
* `SERVER_PORT`: Server port number, e.g. `8000`
## Run server
Either run `main.py`, or run the following command from root directory:
```bash
uvicorn app.main:app
```
To make the server reload after making changes, add the parameter:
```bash
uvicorn app.main:app --reload
```
## API documentation
After running the server, API documentation is available under:
```
http(s)://SERVER_HOST:SERVER:PORT/docs
```
## Database migration
After any changes or additions in database models, new [alembic](https://pypi.org/project/alembic/) revision has to be created using the following command:
```bash
alembic revision --autogenerate -m "example message"
```
And then to upgrade the database to the newest revision:
```bash
alembic upgrade head
```
<file_sep>from fastapi import HTTPException
from fastapi import APIRouter, Depends
from pydantic import EmailStr
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from app.models.user import User as DBUser
from app.api.utils.security import get_current_active_superuser, get_current_user
from app.schemas.msg import Msg
from app.schemas.user import User
from app.utils.email import send_test_email
router = APIRouter()
@router.post("/test-email",
response_model=Msg,
status_code=201,
dependencies=[Depends(get_current_active_superuser)])
def test_email(
email: EmailStr
):
"""
Send test email to given email address
"""
response = send_test_email(email=email)
if response.status_code != 250:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail=f"Error while trying to send email, please try again",
)
return {"msg": "Test email sent"}
@router.post("/test-token",
tags=["tests"],
response_model=User,
dependencies=[Depends(get_current_user)])
def test_token(current_user: DBUser = Depends(get_current_user)):
"""
Test access token
"""
return current_user
<file_sep># Import all the models, so that Base has them before being
# imported by Alembic
from app.database.base import Base
from app.models.user import User
from app.models.exercise import Exercise
<file_sep>from datetime import datetime, timedelta
from typing import Optional
import jwt
from jwt import InvalidTokenError
from app import crud
from app.core import config
from app.schemas.user import User
ALGORITHM = "HS256"
access_token_jwt_subject = "access"
register_token_jwt_subject = "register"
def create_access_token(*, data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire, "sub": access_token_jwt_subject})
encoded_jwt = jwt.encode(to_encode, config.SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def create_register_token(*, data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=30)
to_encode.update({"exp": expire, "sub": register_token_jwt_subject})
encoded_jwt = jwt.encode(to_encode, config.SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
async def verify_register_token(token) -> Optional[str]:
try:
decoded_token = jwt.decode(token, config.SECRET_KEY, algorithms=["HS256"])
assert decoded_token["sub"] == register_token_jwt_subject
return decoded_token["email"]
except InvalidTokenError:
return None
except AssertionError:
return None
def generate_password_reset_token(email, subject):
delta = timedelta(hours=config.EMAIL_RESET_TOKEN_EXPIRE_MINUTES)
now = datetime.utcnow()
expires = now + delta
exp = expires.timestamp()
encoded_jwt = jwt.encode(
{"exp": exp, "nbf": now, "sub": subject, "email": email},
config.SECRET_KEY,
algorithm="HS256",
)
return encoded_jwt
async def verify_password_reset_token(token) -> Optional[str]:
try:
decoded_token = jwt.decode(token, config.SECRET_KEY, algorithms=["HS256"])
record = await crud.user.get_by_email(email=decoded_token["email"])
subject = User(**record).id
assert decoded_token["sub"] == subject
return decoded_token["email"]
except InvalidTokenError:
return None
except AssertionError:
return None
<file_sep>import os
from dotenv import load_dotenv, find_dotenv
def get_env_boolean(var_name, default_value=False):
result = default_value
env_value = os.getenv(var_name)
if env_value is not None:
result = env_value.upper() in ("TRUE", "1")
return result
load_dotenv(find_dotenv())
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 8
EMAIL_RESET_TOKEN_EXPIRE_MINUTES = 15
EMAIL_NEW_ACCOUNT_TOKEN_EXPIRE_MINUTES = 30
DATABASE_URL = os.getenv("DATABASE_URL")
EMAILS_ENABLED = get_env_boolean("EMAILS_ENABLED", True)
EMAIL_TEMPLATES_DIR = "./app/email-templates"
PROJECT_NAME = os.getenv("PROJECT_NAME")
EMAILS_FROM_EMAIL = os.getenv("EMAILS_FROM_EMAIL")
EMAILS_FROM_NAME = PROJECT_NAME
SECRET_KEY = os.getenv("SECRET_KEY")
SERVER_HOST = os.getenv("SERVER_HOST")
SERVER_PORT = int(os.getenv("SERVER_PORT"))
BACKEND_CORS_ORIGINS = os.getenv("BACKEND_CORS_ORIGINS")
SMTP_TLS = get_env_boolean("SMTP_TLS", True)
SMTP_PORT = None
_SMTP_PORT = os.getenv("SMTP_PORT")
if _SMTP_PORT is not None:
SMTP_PORT = int(_SMTP_PORT)
SMTP_HOST = os.getenv("SMTP_HOST")
SMTP_USER = os.getenv("SMTP_USER")
SMTP_PASSWORD = os.getenv("SMTP_PASSWORD")
SUPERUSER = os.getenv("SUPERUSER")
SUPERUSER_PASSWORD = os.getenv("SUPERUSER_PASSWORD")
<file_sep>import logging
from pathlib import Path
from smtplib import SMTPException
from typing import Union
import emails
from emails.backend.response import SMTPResponse
from emails.template import JinjaTemplate
from app.core import config
password_reset_jwt_subject = "preset"
def send_email(email_to: str, subject_template="", html_template="", environment=None) -> Union[SMTPResponse, bool]:
if environment is None:
environment = {}
assert config.EMAILS_ENABLED, "no provided configuration for email variables"
message = emails.Message(
subject=JinjaTemplate(subject_template),
html=JinjaTemplate(html_template),
mail_from=(config.EMAILS_FROM_NAME, config.EMAILS_FROM_EMAIL),
)
smtp_options = {"host": config.SMTP_HOST, "port": config.SMTP_PORT}
if config.SMTP_TLS:
smtp_options["tls"] = True
if config.SMTP_USER:
smtp_options["user"] = config.SMTP_USER
if config.SMTP_PASSWORD:
smtp_options["password"] = config.SMTP_PASSWORD
try:
response = message.send(to=email_to, render=environment, smtp=smtp_options)
assert response.status_code == 250
logging.info(f"Send email result: {response}")
except SMTPException as error:
logging.error(f"Error while trying to send email: {error}")
return False
except AssertionError:
logging.error(f"Failed to send email, send email result: {response}")
return False
return response
def send_test_email(email: str):
project_name = config.PROJECT_NAME
subject = f"{project_name} - Test email"
try:
with open(Path(config.EMAIL_TEMPLATES_DIR) / "test_email.html") as f:
template_str = f.read()
except IOError:
logging.error(f"Unable to open email template path")
return False
return send_email(
email_to=email,
subject_template=subject,
html_template=template_str,
environment={"project_name": config.PROJECT_NAME, "email": email},
)
def send_reset_password_email(email: str, username: str, first_name: str, token: str):
project_name = config.PROJECT_NAME
subject = f"{project_name} - Password recovery for user {username}"
try:
with open(Path(config.EMAIL_TEMPLATES_DIR) / "reset_password.html") as f:
template_str = f.read()
except IOError:
logging.error(f"Unable to open email template path")
return False
if hasattr(token, "decode"):
use_token = token.decode()
else:
use_token = token
server_host = config.SERVER_HOST
link = f"{server_host}/reset-password?token={use_token}"
return send_email(
email_to=email,
subject_template=subject,
html_template=template_str,
environment={
"project_name": config.PROJECT_NAME,
"username": username,
"first_name": first_name,
"valid_minutes": config.EMAIL_RESET_TOKEN_EXPIRE_MINUTES,
"link": link,
},
)
def send_verify_account_email(email: str, username: str, first_name: str, token: str):
project_name = config.PROJECT_NAME
subject = f"{project_name} - Verify account for user {username}"
try:
with open(Path(config.EMAIL_TEMPLATES_DIR) / "verify_account.html") as f:
template_str = f.read()
except IOError:
logging.error(f"Unable to open email template path")
return False
if hasattr(token, "decode"):
use_token = token.decode()
else:
use_token = token
server_host = config.SERVER_HOST
link = f"{server_host}/verify-account?token={use_token}"
return send_email(
email_to=email,
subject_template=subject,
html_template=template_str,
environment={
"project_name": config.PROJECT_NAME,
"username": username,
"first_name": first_name,
"link": link,
"valid_minutes": config.EMAIL_NEW_ACCOUNT_TOKEN_EXPIRE_MINUTES
}
)
def send_new_account_email(email: str, username: str, first_name: str):
project_name = config.PROJECT_NAME
subject = f"{project_name} - Account {username} created successfully"
try:
with open(Path(config.EMAIL_TEMPLATES_DIR) / "new_account.html") as f:
template_str = f.read()
except IOError:
logging.error(f"Unable to open email template path")
return False
link = config.SERVER_HOST
return send_email(
email_to=email,
subject_template=subject,
html_template=template_str,
environment={
"project_name": config.PROJECT_NAME,
"username": username,
"first_name": first_name,
"link": link,
}
)
<file_sep>from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException, Body, Form
from fastapi.security import OAuth2PasswordRequestForm
from pydantic import EmailStr
from starlette.status import HTTP_403_FORBIDDEN, HTTP_404_NOT_FOUND, HTTP_409_CONFLICT, HTTP_500_INTERNAL_SERVER_ERROR
from app import crud
from app.core import config
from app.core.token import create_access_token, generate_password_reset_token, verify_password_reset_token, \
create_register_token, verify_register_token
from app.models.user import User as DBUser
from app.schemas.msg import Msg
from app.schemas.token import Token
from app.schemas.user import UserCreate
from app.utils.email import send_reset_password_email, send_verify_account_email, send_new_account_email
router = APIRouter()
@router.post("/login/access-token",
tags=["login"],
response_model=Token)
async def login_access_token(
form_data: OAuth2PasswordRequestForm = Depends()
):
"""
OAuth2 compatible token login, get an access token for future requests
"""
user = await crud.user.authenticate(
username=form_data.username, password=<PASSWORD>_data.<PASSWORD>
)
if not user:
raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="Incorrect credentials")
elif not user.is_active:
raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Inactive user")
elif not user.is_email_verified:
raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Please verify your account via email")
access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
return {
"access_token": create_access_token(
data={"user_id": user.id}, expires_delta=access_token_expires
),
"token_type": "bearer",
}
@router.post("/register",
tags=["login"],
response_model=Msg)
async def register(
username: str = Form(...),
password: str = Form(...),
email: EmailStr = Form(...),
first_name: str = Form(...),
last_name: str = Form(None)
):
"""
Create new account and send verification email with token to user.
"""
user = await crud.user.get_by_email(email=email)
if user:
raise HTTPException(
status_code=HTTP_409_CONFLICT,
detail="The user with this email already exists in the system",
)
user = await crud.user.get_by_username(username=username)
if user:
raise HTTPException(
status_code=HTTP_409_CONFLICT,
detail="Username already taken",
)
user = UserCreate(username=username,
password=<PASSWORD>,
email=email,
first_name=first_name,
last_name=last_name,
is_email_verified=False
)
user_id = await crud.user.create(user)
register_token = create_register_token(data={"email": user.email})
if send_verify_account_email(
email=user.email, username=user.username, first_name=user.first_name, token=register_token
):
return {"msg": "New account email sent, check your inbox to verify your account"}
else:
await crud.user.remove(user_id)
raise HTTPException(
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
detail="Error while trying to send email, please try again",
)
@router.post("/verify-account",
tags=["login"],
response_model=Msg)
async def verify_account(
token: str = Form(...)
):
"""
Verify account using token.
"""
email = await verify_register_token(token)
if not email:
raise HTTPException(status_code=400, detail="Invalid email verify token")
record = await crud.user.get_by_email(email)
if not record:
raise HTTPException(
status_code=404,
detail="The user with this email does not exist in the system."
)
user = DBUser(**record)
if user.is_email_verified:
raise HTTPException(
status_code=HTTP_409_CONFLICT,
detail="User already verified",
)
await crud.user.update(user.id, {'is_email_verified': True})
send_new_account_email(email=user.email, username=user.username, first_name=user.first_name)
return {"msg": "Account verified"}
@router.post("/recover-password/{email}",
tags=["login"],
response_model=Msg,
status_code=201)
async def recover_password(
email: EmailStr
):
"""
Recover password
"""
record = await crud.user.get_by_email(email=email)
if not record:
raise HTTPException(
status_code=404,
detail="The user with this email does not exist in the system"
)
user = DBUser(**record)
password_reset_token = generate_password_reset_token(email=email, subject=user.id)
send_reset_password_email(
email=user.email, username=user.username, first_name=user.first_name, token=password_reset_token
)
return {"msg": "Password recovery email sent"}
@router.post("/reset-password/",
tags=["login"],
response_model=Msg)
async def reset_password(
token: str = Body(...),
new_password: str = Body(...)
):
"""
Reset password
"""
email = await verify_password_reset_token(token)
if not email:
raise HTTPException(status_code=400, detail="Invalid password reset token")
record = await crud.user.get_by_email(email=email)
if not record:
raise HTTPException(
status_code=404,
detail="The user with this email does not exist in the system",
)
user = DBUser(**record)
if not user.is_active:
raise HTTPException(status_code=400, detail="Inactive user")
user.password = <PASSWORD>
await crud.user.update(user.id, user)
return {"msg": "Password updated successfully"}
<file_sep>from typing import List
from fastapi import APIRouter, Depends, HTTPException
from starlette.status import HTTP_404_NOT_FOUND, HTTP_409_CONFLICT
from app import crud
from app.api.utils.security import get_current_active_user, get_current_active_superuser
from app.models.user import User as DBUser
from app.schemas.msg import Msg
from app.schemas.user import User, UserCreate, UserUpdate
router = APIRouter()
@router.get("",
response_model=List[User],
dependencies=[Depends(get_current_active_superuser)])
async def read_users(
skip: int = 0,
limit: int = 100
):
"""
Retrieve users.
"""
return await crud.user.get_multi(skip, limit)
@router.post("",
response_model=User,
dependencies=[Depends(get_current_active_superuser)],
status_code=201)
async def create_user(
user_in: UserCreate
):
"""
Create new user.
"""
record = await crud.user.get_by_email(email=user_in.email)
if record:
raise HTTPException(
status_code=HTTP_409_CONFLICT,
detail="The user with this email already exists in the system",
)
record = await crud.user.get_by_username(username=user_in.username)
if record:
raise HTTPException(
status_code=HTTP_409_CONFLICT,
detail="Username already taken",
)
user_id = await crud.user.create(obj_in=user_in)
return await crud.user.get(user_id)
@router.get("/me",
response_model=User,
dependencies=[Depends(get_current_active_user)])
async def read_user_me(
current_user: DBUser = Depends(get_current_active_user)
):
"""
Get current user
"""
return current_user
@router.get("/{user_id}",
response_model=User,
dependencies=[Depends(get_current_active_superuser)])
async def read_user_by_id(
user_id: int
):
"""
Get a specific user by id.
"""
user = await crud.user.get(id=user_id)
if not user:
raise HTTPException(
status_code=HTTP_404_NOT_FOUND,
detail="The user does not exist in the system",
)
return user
@router.put("/{user_id}",
response_model=User,
dependencies=[Depends(get_current_active_superuser)])
async def update_user(
user_id: int,
user_in: UserUpdate
):
"""
Update a user.
"""
user = await crud.user.get(id=user_id)
if not user:
raise HTTPException(
status_code=HTTP_404_NOT_FOUND,
detail="The user does not exist in the system",
)
if user_in.email:
other_user = await crud.user.get_by_email(email=user_in.email)
if other_user and (user != other_user):
raise HTTPException(
status_code=HTTP_409_CONFLICT,
detail="The user with this email already exists in the system",
)
if user_in.username:
other_user = await crud.user.get_by_username(username=user_in.username)
if other_user and (user != other_user):
raise HTTPException(
status_code=HTTP_409_CONFLICT,
detail="Username already taken",
)
user_id = await crud.user.update(id=user_id, obj_in=user_in)
return await crud.user.get(id=user_id)
@router.delete("/{user_id}",
response_model=User,
dependencies=[Depends(get_current_active_superuser)])
async def remove_user_by_id(
user_id: int
):
"""
Remove a specific user by id
"""
user = await crud.user.get(id=user_id)
if not user:
raise HTTPException(
status_code=HTTP_404_NOT_FOUND,
detail="The user does not exist in the system",
)
await crud.user.remove(id=user_id)
return user
@router.delete("",
response_model=Msg,
dependencies=[Depends(get_current_active_superuser)])
async def remove_all_users():
"""
Remove all users
"""
await crud.user.remove_all()
return {'msg': 'All users deleted successfully'}
<file_sep>from sqlalchemy import Column, Integer, String
from app.database.base import Base
class Exercise(Base):
id = Column(Integer, primary_key=True, index=True)
name = Column(String, unique=True, index=True)
description = Column(String)
default_reps = Column(Integer, default=8)
<file_sep>from .crud_user import user
from .crud_exercise import exercise
<file_sep>from sqlalchemy import Column, Integer, String, Boolean, DateTime
from app.database.base import Base
class User(Base):
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True)
first_name = Column(String, index=True)
last_name = Column(String, index=True)
username = Column(String, index=True)
hashed_password = Column(String)
date_created = Column(DateTime, index=True)
is_active = Column(Boolean(), default=True)
is_email_verified = Column(Boolean(), default=True)
is_superuser = Column(Boolean(), default=False)
<file_sep>from typing import Optional
from pydantic import BaseModel
class ExerciseBase(BaseModel):
name: Optional[str]
description: Optional[str]
default_reps: Optional[int] = 8
class ExerciseBaseInDB(ExerciseBase):
id: int = None
class ExerciseCreate(ExerciseBase):
name: str
class ExerciseUpdate(ExerciseBase):
pass
class Exercise(ExerciseBaseInDB):
pass
<file_sep>"""edit user table
Revision ID: b19c6cf9b3a9
Revises: <PASSWORD>
Create Date: 2020-03-26 01:22:50.992018
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = 'b19c6cf<PASSWORD>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('email', sa.String(), nullable=True),
sa.Column('first_name', sa.String(), nullable=True),
sa.Column('last_name', sa.String(), nullable=True),
sa.Column('hashed_password', sa.String(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('is_superuser', sa.Boolean(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)
op.create_index(op.f('ix_user_first_name'), 'user', ['first_name'], unique=False)
op.create_index(op.f('ix_user_id'), 'user', ['id'], unique=False)
op.create_index(op.f('ix_user_last_name'), 'user', ['last_name'], unique=False)
op.drop_index('ix_users_id', table_name='users')
op.drop_table('users')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),
sa.Column('first_name', sa.VARCHAR(), autoincrement=False, nullable=True),
sa.Column('last_name', sa.VARCHAR(), autoincrement=False, nullable=True),
sa.Column('age', sa.INTEGER(), autoincrement=False, nullable=True),
sa.Column('email', sa.VARCHAR(), autoincrement=False, nullable=True),
sa.PrimaryKeyConstraint('id', name='users_pkey')
)
op.create_index('ix_users_id', 'users', ['id'], unique=False)
op.drop_index(op.f('ix_user_last_name'), table_name='user')
op.drop_index(op.f('ix_user_id'), table_name='user')
op.drop_index(op.f('ix_user_first_name'), table_name='user')
op.drop_index(op.f('ix_user_email'), table_name='user')
op.drop_table('user')
# ### end Alembic commands ###
|
6d715e839d99784e5f44516a19bffd79a09aea54
|
[
"Markdown",
"Python",
"Text"
] | 26
|
Python
|
lipowskm/simple-workout-tracker-api
|
4a040bedc724da95853a497bcbe3e6a1975c47ca
|
d5f6faf3d9edade8de247edecb32c19e56c92fac
|
refs/heads/master
|
<file_sep>package com.placeholder.annotation;
import java.lang.annotation.*;
import java.lang.reflect.Method;
public class _01UserCaseDemo {
public static void main(String[] args) {
UserCaseProcessor.trackUseCase(PasswordUtils.class);
}
}
class PasswordUtils {
@UserCase(id = 47, description = "Passwords ust contain at least one numeric")
public boolean validatePassword(String password) {
return password.matches("\\w*\\<PASSWORD>");
}
@UserCase(id = 48)
public String encryptPassword(String password) {
return new StringBuilder(password).reverse().toString();
}
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface UserCase {
int id();
String description() default "no description";
}
class UserCaseProcessor {
public static <T> void trackUseCase(Class<T> clazz) {
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method method : declaredMethods) {
UserCase userCase = method.getAnnotation(UserCase.class);
if (userCase != null) {
System.out.println(method.getName() + ": " + userCase.id() + ", " + userCase.description());
}
}
}
}
<file_sep>package com.placeholder.spider;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;
/**
* Created by l on 17-7-13.
*/
public class SinaBlogPageProcessorDemo implements PageProcessor {
private Site site = Site
.me()
.setDomain("blog.sina.com.cn")
.setRetryTimes(3)
.setSleepTime(3000)
.setCharset("UTF-8")
.setUserAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36");
private static final String BLOG_URL_REGEX = "http://blog.sina\\.com\\.cn/s/blog_\\w+\\.html";
private static final String LIST_URL_REGEX= "http://blog\\.sina\\.com\\.cn/s/articlelist_1487828712_0_\\d+\\.html";
@Override
public void process(Page page) {
// 列表页
if(page.getUrl().regex(LIST_URL_REGEX).match()) {
page.addTargetRequests(page.getHtml().links().regex(LIST_URL_REGEX).all());
page.addTargetRequests(page.getHtml().css("div.articleList").links().regex(BLOG_URL_REGEX).all());
// 文章页
} else {
page.putField("title", page.getHtml().xpath("//h2[@class='titName SG_txta']/text()"));
page.putField("content", page.getHtml().xpath("//div[@class='articalContent']"));
page.putField("time", page.getHtml().xpath("//span[@class='time SG_txtc']").regex("\\((.*)\\)"));
}
}
@Override
public Site getSite() {
return site;
}
public static void main(String[] args) {
String baseUrl = "http://blog.sina.com.cn/s/articlelist_1487828712_0_1.html";
baseUrl = "http://blog.sina.com.cn/s/articlelist_1487828712_0_1.html";
Spider.create(new SinaBlogPageProcessorDemo()).addUrl(baseUrl).thread(5).run();
}
}
<file_sep>package com.placeholder.xml.service;
/**
* Created by L on 2018/3/4.
*/
public interface DemoService {
String sayHello(String name);
}
<file_sep>package com.placeholder.concurrent;
import jdk.management.resource.internal.inst.SocketInputStreamRMHooks;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Created by L on 2017/8/7.
* I/O 阻塞的线程不能用interrupt打断,可以通过关闭使线程阻塞的资源来中断线程
*/
public class _16CloseResource {
public static void main(String[] args) throws IOException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(8080);
InputStream is = new Socket("localhost", 8080).getInputStream();
executor.execute(new IOBlocked(is));
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("Shutting down all threads");
executor.shutdownNow();
TimeUnit.SECONDS.sleep(1);
System.out.println("Closing " + is.getClass().getName());
is.close();
}
}
<file_sep>package com.placeholder.dynamic;
import java.lang.invoke.*;
import java.lang.reflect.Method;
/**
* Created by L on 2018/2/23.
*/
public class DynamicTest2 {
public static void main(String[] args) throws Throwable {
MethodType mt = MethodType.methodType(void.class, String.class);
MethodHandle mh = MethodHandles.lookup().findStatic(DynamicTest2.class, "testMethod", mt);
CallSite cs = new ConstantCallSite(mh);
cs.dynamicInvoker().invoke("hello world!");
// mh.invokeExact("hello world!");
}
public static void testMethod(String s) {
System.out.println("testMethod:" + s);
}
}
<file_sep>package com.cooolin.javeweb.web.servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Map;
/**
* Created by l on 17-7-31.
*/
@WebServlet(name="annotation",urlPatterns="/annotation")
public class AnnotationServlet extends HttpServlet {
@Override
public void init() throws ServletException {
System.out.println("init AnnotationServlet");
}
@Override
public void destroy() {
System.out.println("destroy AnnotationServlet");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getCharacterEncoding());
/*Enumeration<String> headerNames = req.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
System.out.println(headerName + ": " + req.getHeader(headerName));
}*/
Map<String, String[]> parameterMap = req.getParameterMap();
System.out.println(req.getProtocol());
BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
resp.getWriter().write("中文annotation get");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Map<String, String[]> parameterMap = req.getParameterMap();
BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
String line;
while ((line=br.readLine()) != null) {
System.out.println(line);
}
resp.getWriter().write("中文annotation post");
}
}
<file_sep>package com.placeholder.io;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
public class _18WatchServiceDemo {
private static final String path = "D:/test";
public static void main(String[] args) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path p = Paths.get(path);
p.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
Thread thread = new Thread(() -> {
try {
while (true) {
WatchKey watchKey = watchService.take();
List<WatchEvent<?>> events = watchKey.pollEvents();
for (WatchEvent<?> event : events) {
Object context = event.context();
WatchEvent.Kind<?> kind = event.kind();
System.out.println("[" + path + "/" + context + "]文件发生了[" + kind + "]事件");
}
watchKey.reset();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.setDaemon(false);
thread.start();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
watchService.close();
} catch (IOException e) {
e.printStackTrace();
}
}));
}
}
<file_sep>package com.placeholder;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebClientOptions;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws IOException {
try (final WebClient webClient = new WebClient()) {
final HtmlPage htmlPage = webClient.getPage("http://angularjs.cn/");
System.out.println(1);
}
}
@Test
public void homePage() throws Exception {
try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
WebClientOptions options = webClient.getOptions();
options.setUseInsecureSSL(true);
options.setJavaScriptEnabled(true);
options.setCssEnabled(true);
options.setThrowExceptionOnScriptError(true);
options.setTimeout(10000);
options.setDoNotTrackEnabled(false);
final HtmlPage page = webClient.getPage("http://angularjs.cn/");
webClient.waitForBackgroundJavaScript(10000);
String xml = page.asXml();
System.out.println(1);
/* final String pageAsXml = page.asXml();
Assert.assertTrue(pageAsXml.contains("<body class=\"composite\">"));
final String pageAsText = page.asText();
Assert.assertTrue(pageAsText.contains("Support for the HTTP and HTTPS protocols"));*/
}
}
}
<file_sep>package com.placeholder.jdbc;
import com.sun.javaws.exceptions.ExitException;
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3306/test";
try (Connection conn = DriverManager.getConnection(url, "root", "123456")) {
long begin = System.currentTimeMillis();
transactionBatchInsert(conn, 100000); //1000000
long end = System.currentTimeMillis();
System.out.println(end - begin + "milliseconds");
}
}
public static void insertByFor(Connection conn, int num) throws SQLException {
Statement statement = conn.createStatement();
for (int i=0; i<num; i++) {
String insertSql = "INSERT INTO person(name) values('" + i + "')";
statement.execute(insertSql);
}
}
public static int[] batchInsert(Connection conn, int num) throws SQLException {
Statement statement = conn.createStatement();
for (int i=0; i<num; i++) {
String insertSql = "INSERT INTO person(name) values('" + i + "')";
statement.addBatch(insertSql);
}
int[] ints = statement.executeBatch();
return ints;
}
public static void transactionInsert(Connection conn, int num) throws SQLException {
conn.setAutoCommit(false);
Statement statement = conn.createStatement();
for (int i=0; i<num; i++) {
String insertSql = "INSERT INTO person(name) values('" + i + "')";
statement.execute(insertSql);
}
conn.commit();
}
public static void transactionBatchInsert(Connection conn, int num) throws SQLException {
conn.setAutoCommit(false);
Statement statement = conn.createStatement();
for (int i=0; i<num; i++) {
String insertSql = "INSERT INTO person(name) values('" + i + "')";
statement.addBatch(insertSql);
}
statement.executeBatch();
conn.commit();
}
// 10k 90ms
// 缺点 Packet for query is too large (130000028 > 16777216)
public static void sqlBatchInsert(Connection conn, int num) throws SQLException {
Statement statement = conn.createStatement();
StringBuilder sb = new StringBuilder("INSERT INTO person(name) VALUES('" + 0 + "')");
for (int i=1; i<num; i++) {
sb.append(",('").append(i).append("')");
}
statement.execute(sb.toString());
}
public static void preparedBatchInsert(Connection conn, int num) throws SQLException {
conn.setAutoCommit(false);
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO person(name) VALUES(?)");
for (int i=0; i<num; i++) {
pstmt.setString(1, i + "");
pstmt.addBatch();
}
pstmt.executeBatch();
conn.commit();
}
}
<file_sep>package com.placeholder.dynamic;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
/**
* Created by L on 2018/2/23.
*/
public class DynamicPerformance {
public static void main(String[] args) throws Throwable {
test();
}
public static void testMethod() {
System.out.println("hello world");
}
public static void test() throws Throwable {
long begin = System.currentTimeMillis();
for (int i=0; i<100; i++) {
reflect();
}
System.out.println(System.currentTimeMillis() - begin);
}
public static void invoke() throws Throwable {
MethodHandle mh = MethodHandles.lookup().findStatic(DynamicPerformance.class, "testMethod", MethodType.methodType(void.class));
mh.invokeExact();
}
public static void reflect() throws Throwable {
DynamicPerformance.class.getMethod("testMethod").invoke(null);
}
}
<file_sep>package com.placeholder.io;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* Created by L on 2017/8/18.
*/
public class _06GetChannel {
private static final int BSIZE = 1024;
public static void main(String[] args) throws IOException {
String filepath = "C:/Users/L/Desktop/data.txt";
FileChannel fc = new FileOutputStream(filepath).getChannel();
fc.write(ByteBuffer.wrap("Some text ".getBytes()));
fc.close();
fc = new FileInputStream(filepath).getChannel();
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
fc.read(buffer);
// The limit is set to the current position and then the position is set to zero.
buffer.flip();
while (buffer.hasRemaining())
System.out.print((char)buffer.get());
}
}
<file_sep>package com.placeholder.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by L on 2017/8/3.
*/
public class _03SingleThreadPool {
public static void main(String[] args) {
// 使用一个线程执行五个任务,相
ExecutorService executor = Executors.newSingleThreadExecutor();
for (int i=0; i<5; i++)
executor.execute(new _01LiftOff());
executor.shutdown();
}
}
<file_sep>package com.placeholder.concurrent;
import com.sun.org.apache.xpath.internal.SourceTree;
import sun.util.resources.cldr.so.CurrencyNames_so;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.*;
/**
* Created by L on 2017/8/9.
*/
public class _31BankTellerSimulation {
private static final int MAX_LINE_SIZE = 50;
private static final int ADJUSTMENT_PERIOD = 1000;
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
CustomerLine customers = new CustomerLine(MAX_LINE_SIZE);
executor.execute(new CustomerGenerator(customers));
executor.execute(new TellerManager(executor, customers, ADJUSTMENT_PERIOD));
Thread.sleep(5000);
executor.shutdownNow();
}
}
class Customer {
private final int serveTime;
public Customer(int serveTime) {
this.serveTime = serveTime;
}
public int getServeTime() {
return serveTime;
}
public String toString() {
return "[" + serveTime + "]";
}
}
class CustomerLine extends ArrayBlockingQueue<Customer> {
public CustomerLine(int maxCustomerLine) {
super(maxCustomerLine);
}
@Override
public String toString() {
if (this.isEmpty())
return "[Empty]";
StringBuilder sb = new StringBuilder();
for (Customer customer : this)
sb.append(customer);
return sb.toString();
}
}
class CustomerGenerator implements Runnable {
private CustomerLine customers;
private static final Random rand = new Random(47);
public CustomerGenerator(CustomerLine customers) {
this.customers = customers;
}
public void run() {
try {
while (!Thread.interrupted()) {
TimeUnit.MILLISECONDS.sleep(300);
customers.put(new Customer(rand.nextInt(1000)));
}
} catch (InterruptedException e) {
System.out.println("CustomerGenerator interrupted");
}
System.out.println("CustomerGenerator finished");
}
}
class Teller implements Runnable, Comparable<Teller> {
private static int counter = 0;
private int id = counter++;
private boolean isServe = true;
private int serveCount = 0;
private CustomerLine customers;
public Teller(CustomerLine customers) {
this.customers = customers;
}
public void run() {
try {
while (!Thread.interrupted()) {
Customer customer = customers.take();
TimeUnit.MILLISECONDS.sleep(customer.getServeTime());
synchronized (this) {
serveCount++;
while (!isServe)
wait();
}
}
} catch (InterruptedException e) {
System.out.println(this + " interrupted");
}
System.out.println(this + "finish");
}
public synchronized void doSomethingElse() {
serveCount = 0;
isServe = false;
}
public synchronized void serveCustomer() {
assert !isServe : "already serving: " + this;
isServe = true;
notifyAll();
}
public String toString() {
return "Teller " + id + " ";
}
public String shortString() {
return "T" + id;
}
public synchronized int compareTo(Teller o) {
return serveCount - o.serveCount;
}
}
class TellerManager implements Runnable {
private ExecutorService executor;
private PriorityBlockingQueue<Teller> workingTellers = new PriorityBlockingQueue<>();
private Queue<Teller> tellersDoingOtherThings = new LinkedList<>();
private CustomerLine customers;
private static Random rand = new Random(47);
private int period;
public TellerManager(ExecutorService executor, CustomerLine customers, int period) {
// this.tellers = tellers;
this.executor = executor;
this.period = period;
this.customers = customers;
Teller teller = new Teller(customers);
executor.execute(teller);
workingTellers.add(teller);
}
public void adjuestNumber() throws InterruptedException {
if (customers.size() / workingTellers.size() > 2) {
if (tellersDoingOtherThings.isEmpty()) {
Teller teller = new Teller(customers);
executor.execute(teller);
workingTellers.add(teller);
} else {
Teller teller = tellersDoingOtherThings.remove();
teller.serveCustomer();
workingTellers.add(teller);
}
}
if (workingTellers.size() > 1 && customers.size() / workingTellers.size() < 2) {
reassignOneTeller();
}
if (customers.isEmpty()) {
while (workingTellers.size() > 1)
reassignOneTeller();
}
}
public void reassignOneTeller() {
Teller teller = workingTellers.poll();
teller.doSomethingElse();
tellersDoingOtherThings.offer(teller);
}
public void run() {
try {
while (!Thread.interrupted()) {
TimeUnit.MILLISECONDS.sleep(period);
adjuestNumber();
System.out.print(customers + " { ");
for (Teller teller : workingTellers)
System.out.print(teller.shortString() + " ");
System.out.println("}");
}
} catch (InterruptedException e) {
System.out.println("TellerManager interrupted");
}
System.out.println(this + "finish");
}
public String toString() {
return "TellerManager ";
}
}<file_sep>package com.cooolin.springmvc.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
/**
* Created by l on 17-7-31.
*/
@RestController
public class TestController {
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(HttpServletRequest request) {
Enumeration<String> e = request.getAttributeNames();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
System.out.println("============");
System.out.println(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
System.out.println(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME);
Object obj = request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
AnnotationConfigWebApplicationContext ctx = (AnnotationConfigWebApplicationContext) obj;
return "test";
}
@RequestMapping(value = "/form", method = RequestMethod.POST)
public String form(@RequestBody Test test) {
System.out.println(test);
return "result";
}
}
class Test {
private int id;
private String name;
public Test(int id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return "{ id: " + id + ", name: " + name + " }";
}
}
<file_sep>package com.placeholder.dynamic;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
/**
* Created by L on 2018/2/22.
*/
public class DynamicTest {
public static void main(String[] args) throws Throwable {
// Object obj = new ClassA();
Object obj = System.out;
getPrintlnMH(obj).invokeExact("hello");
}
private static MethodHandle getPrintlnMH(Object obj) throws Exception {
MethodType mt = MethodType.methodType(void.class, String.class);
return MethodHandles.lookup().findVirtual(obj.getClass(), "println", mt).bindTo(obj);
}
static class ClassA {
public void println(String s) {
System.out.println("class A:" + s);
}
}
}
<file_sep>package com.placeholder;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.state.SessionState;
import org.apache.activemq.usage.StoreUsage;
import org.springframework.jms.core.JmsTemplate;
import redis.clients.jedis.*;
import javax.jms.*;
import javax.jms.Connection;
import java.lang.annotation.*;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Demo {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
A a = new A();
executor.submit(a::a);
executor.submit(a::a);
}
}
class A {
public synchronized void a() {
while (true) {
try {
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread() + " hello");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
<file_sep>package com.placeholder.java;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import com.placeholder.xml.provider.DemoServiceImpl;
import com.placeholder.xml.service.DemoService;
import java.io.IOException;
/**
* Created by L on 2018/3/4.
*/
public class ProviderMain {
public static void main(String[] args) throws IOException {
DemoService demoService = new DemoServiceImpl();
ApplicationConfig application = new ApplicationConfig();
application.setName("providerapplication");
// registry
RegistryConfig registry = new RegistryConfig();
registry.setAddress("multicast://172.16.58.3:1234");
// registry.setUsername("username");
// registry.setPassword("<PASSWORD>");
ProtocolConfig protocol = new ProtocolConfig();
protocol.setName("dubbo");
protocol.setPort(20880);
ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>();
serviceConfig.setApplication(application);
serviceConfig.setRegistry(registry); // 多个注册中心可以用setRegistries()
serviceConfig.setProtocol(protocol); // 多个协议可以用setProtocols()
serviceConfig.setInterface(DemoService.class);
serviceConfig.setRef(demoService);
// serviceConfig.setVersion("1.0.0");
serviceConfig.export();
System.in.read();
}
}
<file_sep>package com.placeholder.io;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by L on 2017/8/20.
*
* 比较不提供方式的序列化的引用是否相同
*/
public class _017SerializationReference {
public static void main(String[] args) throws IOException, ClassNotFoundException {
House house = new House();
List<Animal> animals = new ArrayList<>();
animals.add(new Animal("dog", house));
animals.add(new Animal("hamster", house));
animals.add(new Animal("cat", house));
System.out.println("animals: " + animals);
// write
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
ObjectOutputStream oos1 = new ObjectOutputStream(baos1);
oos1.writeObject(animals);
oos1.writeObject(animals);
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
ObjectOutputStream oos2 = new ObjectOutputStream(baos2);
oos2.writeObject(animals);
// read
ObjectInputStream ois1 = new ObjectInputStream(new ByteArrayInputStream(baos1.toByteArray()));
List animals1 = (List) ois1.readObject();
List animals2 = (List) ois1.readObject();
ObjectInputStream ois2 = new ObjectInputStream(new ByteArrayInputStream(baos2.toByteArray()));
List animals3 = (List) ois2.readObject();
System.out.println(animals1);
System.out.println(animals2);
System.out.println(animals3);
}
}
class House implements Serializable {
}
class Animal implements Serializable {
private String name;
private House preferredHouse;
Animal(String name, House h) {
this.name = name;
this.preferredHouse = h;
}
public String toString() {
return name + "[" + super.toString() + "], " + preferredHouse + "\n";
}
}<file_sep>package com.placeholder.io;
import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* Created by L on 2017/8/20.
*/
public class _12GZIPcompress {
private static String path = "C:/Users/L/Desktop/";
public static void main(String[] args) throws IOException, InterruptedException {
// 写 data.txt
BufferedWriter out = new BufferedWriter(new FileWriter(path + "data.txt"));
out.write("hello中文world");
out.flush();
out.close();
// data.txt 压缩成 data.gz
BufferedInputStream in = new BufferedInputStream(new FileInputStream(path + "data.txt"));
BufferedOutputStream out2 = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(path + "data.gz")));
System.out.println("Writing file");
int c;
while ((c = in.read()) != -1) {
out2.write(c);
}
in.close();
out2.close();
// 读取data.gz
System.out.println("Reading file");
BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(path + "data.gz"))));
String s;
while ((s = in2.readLine()) != null) {
System.out.println(s);
}
}
}
<file_sep>package com.placeholder.annotation.service;
/**
* Created by L on 2018/3/4.
*/
public interface AnnotationService {
String sayHello(String name);
}
<file_sep>package com.placeholder.rbtree;
import java.util.*;
public class RedBlackTree<K extends Comparable<K>, V> implements Map<K, V> {
private RedBlackTreeNode<K, V> root;
private int size;
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean containsKey(Object key) {
// TODO: 2020/4/12
return false;
}
@Override
public boolean containsValue(Object value) {
// TODO: 2020/4/12
return false;
}
@Override
public V get(Object key) {
// TODO: 2020/4/12
return null;
}
@Override
public V put(K key, V value) {
RedBlackTreeNode<K, V> addNode = insert(key, value);
if (addNode != null) {
fixAfterInsert(addNode);
}
// TODO: 2020/4/12
return null;
}
private void fixAfterInsert(RedBlackTreeNode<K, V> node) {
if (node == null) {
return;
}
RedBlackTreeNode<K, V> p;
while ((p = node.getParent()) != null && p.isRed()) {
if (p.getParent().getLeft() == p) {
// 父节点为左节点
RedBlackTreeNode<K, V> sib = p.getParent().getRight();
if (sib != null && sib.isRed()) {
sib.setRed(false);
p.setRed(false);
p.getParent().setRed(true);
node = p.getParent();
} else {
if (p.getRight() == node) {
node = p;
leftRotate(node);
}
node.getParent().setRed(false);
node.getParent().getParent().setRed(true);
rightRotate(p.getParent().getParent());
break;
}
} else {
// 对称
RedBlackTreeNode<K, V> sib = p.getParent().getLeft();
if (sib != null && sib.isRed()) {
sib.setRed(false);
p.setRed(false);
p.getParent().setRed(true);
node = p.getParent();
} else {
if (p.getLeft() == node) {
node = p;
rightRotate(node);
}
node.getParent().setRed(false);
node.getParent().getParent().setRed(true);
leftRotate(node.getParent().getParent());
break;
}
}
}
root.setRed(false);
}
private void leftRotate(RedBlackTreeNode<K, V> node) {
if (node != null) {
RedBlackTreeNode<K, V> r = node.getRight();
node.setRight(r.getLeft());
if (node.getRight() != null) {
node.getRight().setParent(node);
}
if (node.getParent() == null) {
root = r;
} else if (node.getParent().getLeft() == node) {
node.getParent().setLeft(r);
} else {
node.getParent().setRight(r);
}
r.setLeft(node);
r.setParent(node.getParent());
node.setParent(r);
}
}
private void rightRotate(RedBlackTreeNode<K, V> node) {
if (node != null) {
RedBlackTreeNode<K, V> l = node.getLeft();
node.setLeft(l.getRight());
if (node.getLeft() != null) {
node.getLeft().setParent(node);
}
if (node.getParent() == null) {
root = l;
} else if (node.getParent().getLeft() == node) {
node.getParent().setLeft(l);
} else {
node.getParent().setRight(l);
}
l.setRight(node);
l.setParent(node.getParent());
node.setParent(l);
}
}
private RedBlackTreeNode<K, V> insert(K key, V value) {
if (root == null) {
size++;
root = new RedBlackTreeNode<>(key, value, null);
return root;
}
RedBlackTreeNode<K, V> p;
RedBlackTreeNode<K, V> c = root;
do {
int cmp = key.compareTo(c.getKey());
p = c;
if (cmp == 0) {
c.setValue(value);
return null;
} else if (cmp > 0) {
c = c.getRight();
} else {
c = c.getRight();
}
} while (c != null);
RedBlackTreeNode<K, V> addNode = new RedBlackTreeNode<>(key, value, p);
int cmp = key.compareTo(p.getKey());
addNode.setParent(p);
if (cmp > 0) {
p.setRight(addNode);
} else {
p.setLeft(addNode);
}
size++;
return addNode;
}
private RedBlackTreeNode<K, V> find(K key) {
RedBlackTreeNode<K, V> n = root;
while (n != null) {
int cmp = key.compareTo(n.getKey());
if (cmp == 0) {
break;
} else if (cmp > 0) {
n = n.getRight();
} else {
n = n.getLeft();
}
}
return n;
}
@Override
public V remove(Object key) {
K k = (K) key;
if (k == null) {
return null;
}
RedBlackTreeNode<K, V> toDelete = find(k);
if (toDelete == null) {
return null;
}
if (toDelete.getRight() != null) {
// 如果有后继节点,则与后继节点交换位置,
RedBlackTreeNode<K, V> s = toDelete.getRight();
while (s.getLeft() != null) {
s = s.getLeft();
}
toDelete.setKey(s.getKey());
toDelete.setValue(s.getValue());
toDelete = s;
}
if (toDelete.getLeft() == null && toDelete.getRight() == null) {
fixAfterDelete(toDelete);
} else {
// 1、子节点有红色,可以交换位置 TODO:
RedBlackTreeNode<K, V> c = toDelete.getLeft() != null ? toDelete.getLeft() : toDelete.getRight();
toDelete.setKey(c.getKey());
toDelete.setValue(c.getValue());
toDelete = c;
}
// 删除节点
if (toDelete.getParent() != null) {
if (toDelete.getParent().getLeft() == toDelete) {
toDelete.getParent().setLeft(null);
} else {
toDelete.getParent().setRight(null);
}
}
toDelete.setParent(null);
size--;
if (root != null) {
root.setRed(false);
}
return null;
}
private void fixAfterDelete(RedBlackTreeNode<K, V> node) {
// 如果当前是黑色,删除了就会违法【黑高相同】规则,需要借一个
// 1、子节点有红色,可以交换位置 TODO:
// 2、兄弟节点借一个
// 3、父节点借一个
while (!node.isRed() && node.getParent() != null) {
RedBlackTreeNode<K, V> p = node.getParent();
if (p.getLeft() == node) {
RedBlackTreeNode<K, V> sib = p.getRight();
if (sib.isRed()) {
sib.setRed(false);
p.setRed(true);
leftRotate(p);
sib = p.getRight();
}
if (!isRed(sib.getLeft()) && !isRed(sib.getRight())) { // 兄弟节点为2-node
sib.setRed(true);
// node节点为被删节点或者被子节点借过去的节点,所以不变红
// node.setRed(true);
if (p.isRed()) {
// 如果父节点为红色,则直接借一个。结束循环,黑色,说明父节点是2-node,需要继续循环
p.setRed(false);
break;
} else {
p.setRed(false);
node = p; //继续循环
}
} else { // 兄弟节点为3/4-node
if (!isRed(sib.getRight())) { // 右节点非红,把右节点变红
sib.getLeft().setRed(false);
sib.setRed(true);
rightRotate(sib);
sib = p.getRight();
}
sib.setRed(p.isRed());
p.setRed(false);
sib.getRight().setRed(false);
leftRotate(p);
break;
}
} else {
// 对称
RedBlackTreeNode<K, V> sib = p.getLeft();
if (sib.isRed()) {
sib.setRed(false);
p.setRed(true);
rightRotate(p);
sib = p.getLeft();
}
if (!isRed(sib.getLeft()) && !isRed(sib.getRight())) { // 兄弟节点为2-node
sib.setRed(true);
// node节点为被删节点或者被子节点借过去的节点,所以不变红
// node.setRed(true);
if (p.isRed()) {
// 如果父节点为红色,则直接借一个。结束循环,黑色,说明父节点是2-node,需要继续循环
p.setRed(false);
break;
} else {
node = p; //继续循环
}
} else { // 兄弟节点为3/4-node
if (!isRed(sib.getLeft())) { // 右节点非红,把右节点变红
sib.getRight().setRed(false);
sib.setRed(true);
leftRotate(sib);
sib = p.getLeft();
}
sib.setRed(p.isRed());
p.setRed(false);
sib.getLeft().setRed(false);
rightRotate(p);
break;
}
}
}
}
private boolean isRed(RedBlackTreeNode<K, V> node) {
return node != null && node.isRed();
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
// TODO: 2020/4/12
}
@Override
public void clear() {
// TODO: 2020/4/12
}
@Override
public Set<K> keySet() {
// TODO: 2020/4/12
return null;
}
@Override
public Collection<V> values() {
// TODO: 2020/4/12
return null;
}
@Override
public Set<Entry<K, V>> entrySet() {
// TODO: 2020/4/12
return null;
}
/*============================ 校验树结构 =============================*/
public void check() {
checkParent();
checkOrder();
checkBlackHeight();
}
public void checkBlackHeight() {
checkBlackHeight(Collections.singletonList(root));
}
private void checkBlackHeight(List<RedBlackTreeNode<K, V>> nodes) {
boolean exists = getChildren(nodes.get(0)).get(0) != null;
List<RedBlackTreeNode<K, V>> children = new ArrayList<>();
for (RedBlackTreeNode<K, V> node : nodes) {
List<RedBlackTreeNode<K, V>> c1 = getChildren(node);
for (RedBlackTreeNode<K, V> c : c1) {
if ((c == null) == exists) {
throw new RedBlackTreeException("checkBlackHeight");
}
}
children.addAll(c1);
}
if (exists) {
checkBlackHeight(children);
}
}
private List<RedBlackTreeNode<K, V>> getChildren(RedBlackTreeNode<K, V> node) {
ArrayList<RedBlackTreeNode<K, V>> children = new ArrayList<>();
if (node.getLeft() != null && node.getLeft().isRed()) {
children.add(node.getLeft().getLeft());
children.add(node.getLeft().getRight());
} else {
children.add(node.getLeft());
}
if (node.getRight() != null && node.getRight().isRed()) {
children.add(node.getRight().getLeft());
children.add(node.getRight().getRight());
} else {
children.add(node.getRight());
}
return children;
}
public void checkOrder() {
checkOrder(root);
}
private void checkOrder(RedBlackTreeNode<K, V> node) {
if (node == null) {
return;
}
if (node.getLeft() != null && node.getLeft().getKey().compareTo(node.getKey()) > 0) {
throw new RedBlackTreeException("checkOrder");
}
if (node.getRight() != null && node.getRight().getKey().compareTo(node.getKey()) < 0) {
throw new RedBlackTreeException("checkOrder");
}
checkOrder(node.getLeft());
checkOrder(node.getRight());
}
public void checkParent() {
checkParent(root);
}
private void checkParent(RedBlackTreeNode<K, V> node) {
if (node == null) {
return;
}
if (node.getLeft() != null && node.getLeft().getParent() != node) {
throw new RedBlackTreeException("checkParent");
}
if (node.getRight() != null && node.getRight().getParent() != node) {
throw new RedBlackTreeException("checkParent");
}
checkParent(node.getLeft());
checkParent(node.getRight());
}
public static void main(String[] args) {
new RedBlackTree().buildTree();
}
public void buildTree() {
RedBlackTree<Integer, Integer> tree = new RedBlackTree<>();
tree.size = 21;
RedBlackTreeNode<Integer, Integer> node8 = tree.root = new RedBlackTreeNode<>(8, null, false, null);
RedBlackTreeNode<Integer, Integer> node4 = node8.left = new RedBlackTreeNode<>(4, null, false, node8);
RedBlackTreeNode<Integer, Integer> node12 = node8.right = new RedBlackTreeNode<>(12, null, false, node8);
RedBlackTreeNode<Integer, Integer> node2 = node4.left = new RedBlackTreeNode<>(2, null, false, node4);
RedBlackTreeNode<Integer, Integer> node6 = node4.right = new RedBlackTreeNode<>(6, null, false, node4);
RedBlackTreeNode<Integer, Integer> node1 = node2.left = new RedBlackTreeNode<>(1, null, false, node2);
RedBlackTreeNode<Integer, Integer> node3 = node2.right = new RedBlackTreeNode<>(3, null, false, node2);
RedBlackTreeNode<Integer, Integer> node5 = node6.left = new RedBlackTreeNode<>(5, null, false, node6);
RedBlackTreeNode<Integer, Integer> node7 = node6.right = new RedBlackTreeNode<>(7, null, false, node6);
RedBlackTreeNode<Integer, Integer> node10 = node12.left = new RedBlackTreeNode<>(10, null, false, node12);
RedBlackTreeNode<Integer, Integer> node16 = node12.right = new RedBlackTreeNode<>(16, null, true, node12);
RedBlackTreeNode<Integer, Integer> node9 = node10.left = new RedBlackTreeNode<>(9, null, false, node10);
RedBlackTreeNode<Integer, Integer> node11 = node10.right = new RedBlackTreeNode<>(11, null, false, node10);
RedBlackTreeNode<Integer, Integer> node14 = node16.left = new RedBlackTreeNode<>(14, null, false, node16);
RedBlackTreeNode<Integer, Integer> node20 = node16.right = new RedBlackTreeNode<>(20, null, false, node16);
RedBlackTreeNode<Integer, Integer> node13 = node14.left = new RedBlackTreeNode<>(13, null, false, node14);
RedBlackTreeNode<Integer, Integer> node15 = node14.right = new RedBlackTreeNode<>(15, null, false, node14);
RedBlackTreeNode<Integer, Integer> node18 = node20.left = new RedBlackTreeNode<>(18, null, true, node20);
RedBlackTreeNode<Integer, Integer> node21 = node20.right = new RedBlackTreeNode<>(21, null, false, node20);
RedBlackTreeNode<Integer, Integer> node17 = node18.left = new RedBlackTreeNode<>(17, null, false, node18);
RedBlackTreeNode<Integer, Integer> node19 = node18.right = new RedBlackTreeNode<>(19, null, false, node18);
// tree.remove(10);
tree.remove(14);
tree.check();
}
}
class RedBlackTreeException extends RuntimeException {
public RedBlackTreeException(String message) {
super(message);
}
}
class RedBlackTreeNode<K, V> {
K key;
V value;
boolean red = true;
RedBlackTreeNode<K, V> left;
RedBlackTreeNode<K, V> right;
RedBlackTreeNode<K, V> parent;
RedBlackTreeNode(K key, V value, boolean red, RedBlackTreeNode<K,V> parent) {
this.key = key;
this.value = value;
this.red = red;
this.parent = parent;
}
RedBlackTreeNode(K key, V value, RedBlackTreeNode<K,V> parent) {
this.key = key;
this.value = value;
this.parent = parent;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public boolean isRed() {
return red;
}
public void setRed(boolean red) {
this.red = red;
}
public RedBlackTreeNode<K, V> getLeft() {
return left;
}
public void setLeft(RedBlackTreeNode<K, V> left) {
this.left = left;
}
public RedBlackTreeNode<K, V> getRight() {
return right;
}
public void setRight(RedBlackTreeNode<K, V> right) {
this.right = right;
}
public RedBlackTreeNode<K, V> getParent() {
return parent;
}
public void setParent(RedBlackTreeNode<K, V> parent) {
this.parent = parent;
}
}<file_sep>package com.placeholder;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
/**
* Created by L on 2018/2/20.
*/
public class Reference {
private final static int MB = 1 << 20;
/*
* -Xmx20M -Xms20M -XX:+PrintGCDetails
* */
public static void main(String[] args) {
String a = new StringBuilder("com.placeholder.").append("Demo").toString();
System.out.println(a == a.intern());
// weak();
}
public static void soft () {
SoftReference sr = new SoftReference<>(new byte[10 * MB]);
// byte[] b1 = new byte[10 * MB];
// SoftReference soft = new SoftReference(b1);
System.out.println(sr.get());
System.gc();
System.out.println(sr.get());
byte[] b2 = new byte[10 * MB];
System.out.println(sr.get());
}
public static void weak() {
WeakReference wr = new WeakReference<>(new byte[10 * MB]);
// byte[] b1 = new byte[10 * MB];
// WeakReference wr = new WeakReference<>(b1);
System.out.println(wr.get());
System.gc();
System.out.println(wr.get());
}
public static void phantom() {
// TODO: 2018/2/19
}
}
<file_sep>package com.placeholder.concurrent;
import java.util.Random;
import java.util.concurrent.*;
/**
* Created by L on 2017/8/8.
*/
public class _21ToastOMatic {
public static void main(String[] args) throws InterruptedException {
ToastQueue
toastQueue = new ToastQueue(),
butteredQueue = new ToastQueue(),
jammedQueue = new ToastQueue();
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new Toaster(toastQueue));
executor.execute(new Butterer(toastQueue, butteredQueue));
executor.execute(new Jammer(butteredQueue, jammedQueue));
executor.execute(new Eater(jammedQueue));
TimeUnit.SECONDS.sleep(5);
executor.shutdownNow();
}
}
class Toast {
public enum Status { DRY, BUTTERED, JAMMED }
private Status status = Status.DRY;
private final int id;
public Toast(int id) {
this.id = id;
}
public void butter() {
status = Status.BUTTERED;
}
public void jam() {
status = Status.JAMMED;
}
public Status getStatus() {
return status;
}
public int getId() {
return id;
}
public String toString() {
return "Toast " + id + ": " + status + " ";
}
}
class ToastQueue extends LinkedBlockingQueue<Toast> {
}
class Toaster implements Runnable {
private ToastQueue toastQueue;
private int count =0;
private Random rand = new Random(47);
public Toaster(ToastQueue toastQueue) {
this.toastQueue = toastQueue;
}
public void run() {
try {
while (!Thread.interrupted()) {
TimeUnit.MILLISECONDS.sleep(100 + rand.nextInt(500));
Toast toast = new Toast(count++);
System.out.print(toast);
toastQueue.put(toast);
}
} catch (InterruptedException e) {
System.out.println("interrupted during toast");
}
System.out.println("Toaster off");
}
}
class Butterer implements Runnable {
private ToastQueue toastQueue, butteredQueue;
public Butterer(ToastQueue toastQueue, ToastQueue butteredQueue) {
this.toastQueue = toastQueue;
this.butteredQueue = butteredQueue;
}
public void run() {
try {
while (!Thread.interrupted()) {
Toast toast = toastQueue.take();
toast.butter();
System.out.print(toast);
butteredQueue.put(toast);
}
} catch (InterruptedException e) {
System.out.println("interrupted during butter");
}
System.out.println("Butter off");
}
}
class Jammer implements Runnable {
private ToastQueue butteredQueue, jammedQueue;
public Jammer(ToastQueue butteredQueue, ToastQueue jammedQueue) {
this.butteredQueue = butteredQueue;
this.jammedQueue = jammedQueue;
}
public void run() {
try {
while (!Thread.interrupted()) {
Toast toast = butteredQueue.take();
toast.jam();
System.out.print(toast);
jammedQueue.put(toast);
}
} catch (InterruptedException e) {
System.out.println("interrupted during jam");
}
}
}
class Eater implements Runnable {
private ToastQueue jammedQueue;
private int counter = 0;
public Eater(ToastQueue jammedQueue) {
this.jammedQueue = jammedQueue;
}
public void run() {
try {
while (!Thread.interrupted()) {
Toast toast = jammedQueue.take();
if (counter++ != toast.getId() || toast.getStatus() != Toast.Status.JAMMED) {
System.out.println(">>>> Error: " + toast);
System.exit(1);
} else {
System.out.println("Chomp! " + toast);
}
}
} catch (InterruptedException e) {
System.out.println("interrupted during eat");
}
System.out.println("Eat Off");
}
}<file_sep>package com.placeholder.spider;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.FilePipeline;
import us.codecraft.webmagic.pipeline.JsonFilePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.HtmlNode;
import us.codecraft.webmagic.selector.Selectable;
import java.time.LocalDateTime;
/**
* Created by l on 17-7-12.
*/
public class HengyiPageProcessor implements PageProcessor {
private Site site = Site.me().setRetryTimes(3).setSleepTime(100).setCharset("UTF-8");
/**
* @see Spider
* @param page 页面
*/
@Override
public void process(Page page) {
Selectable xpath = page.getHtml().xpath("//script").regex("src=\"([\\w/\\.]+)\"");
page.putField("js", xpath.all());
}
@Override
public Site getSite() {
return site;
}
public static void main(String[] args) {
Spider.create(new HengyiPageProcessor()).addUrl("http://192.168.0.180/#/").addPipeline(new JsonFilePipeline("spider/result")).thread(5).run();
}
}
<file_sep>package com.cooolin.javeweb.web.servlet;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by l on 17-7-31.
*/
@WebServlet(value="/async2", asyncSupported=true)
public class AsyncServlet2 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
final PrintWriter writer = resp.getWriter();
writer.println("异步之前输出的内容。");
writer.flush();
//开始异步调用,获取对应的AsyncContext。
final AsyncContext asyncContext = req.startAsync();
//设置超时时间,当超时之后程序会尝试重新执行异步任务,即我们新起的线程。
asyncContext.setTimeout(10 * 1000L);
//新起线程开始异步调用,start方法不是阻塞式的,它会新起一个线程来启动Runnable接口,之后主程序会继续执行
asyncContext.start(() -> {
try {
Thread.sleep(2 * 1000L);
writer.println("异步调用之后输出的内容。");
writer.flush();
//异步调用完成,如果异步调用完成后不调用complete()方法的话,异步调用的结果需要等到设置的超时
//时间过了之后才能返回到客户端。
asyncContext.complete();
} catch (Exception e) {
e.printStackTrace();
}
});
writer.println("可能在异步调用前输出,也可能在异步调用之后输出,因为异步调用会新起一个线程。");
writer.flush();
}
}
<file_sep>package com.placeholder.concurrent;
import java.util.List;
import java.util.concurrent.*;
/**
* Created by L on 2017/8/9.
*/
public class _30ExchangerDemo {
static int size = 10;
static int delay = 5;
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
Exchanger<List<Fat>> ec = new Exchanger<>();
List<Fat>
producerList = new CopyOnWriteArrayList<>(),
consumerList = new CopyOnWriteArrayList<>();
executor.execute(new ExchangerProducer<>(ec, BasicGenerator.create(Fat.class), producerList));
executor.execute(new ExchangerConsumer<>(ec, consumerList));
TimeUnit.SECONDS.sleep(delay);
executor.shutdownNow();
}
}
class ExchangerProducer<T> implements Runnable {
private Generator<T> generator;
private Exchanger<List<T>> exchanger;
private List<T> holder;
public ExchangerProducer(Exchanger<List<T>> exchanger, Generator<T> gen, List<T> holder) {
this.exchanger = exchanger;
this.generator = gen;
this.holder = holder;
}
public void run() {
try {
while (!Thread.interrupted()) {
for (int i=0; i<_30ExchangerDemo.size; i++) {
holder.add(generator.next());
}
// Exchange full for empty
holder = exchanger.exchange(holder);
}
} catch(InterruptedException e) {
System.out.println("ExchangeProducer interrupted");
}
}
}
class ExchangerConsumer<T> implements Runnable {
private Exchanger<List<T>> exchanger;
private List<T> holder;
private volatile T value;
ExchangerConsumer(Exchanger<List<T>> ex, List<T> holder) {
this.exchanger = ex;
this.holder = holder;
}
public void run() {
try {
while (!Thread.interrupted()) {
holder = exchanger.exchange(holder);
for (T t : holder) {
value = t;
holder.remove(t);
}
}
} catch (InterruptedException e) {
System.out.println("ExchangerConsumer interrupted");
}
System.out.println("Final value: " + value);
}
}
interface Generator<T> {
T next();
}
/*class BasicGenerator implements Generator<T> {
private Class<T> clazz;
public T next() {
T t = null;
try {
t = T.class.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return t;
}
private BasicGenerator(Class<T> c) {
this.clazz = c;
}
public static Generator<T> create(Class<T> c) {
return new BasicGenerator(c);
}
}*/
class BasicGenerator<T> implements Generator<T> {
private Class<T> clazz;
public T next() {
T t = null;
try {
t = clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return t;
}
private BasicGenerator(Class<T> c) {
this.clazz = c;
}
public static <V> BasicGenerator<V> create(Class<V> c) {
return new BasicGenerator<>(c);
}
}
<file_sep>package com.placeholder;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Created by L on 2017/8/14.
*/
public class MQTest {
static String DEFAULTUSER = ActiveMQConnection.DEFAULT_USER;
static String DEFAULTPASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
static String DEFAULTBROKERURL = ActiveMQConnection.DEFAULT_BROKER_URL;
public static void main(String[] args) {
try {
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new com.placeholder.MQProducer());
executor.execute(new com.placeholder.MQConsumer());
// TimeUnit.SECONDS.sleep(10);
// executor.shutdownNow();
} catch (Exception e) {
System.out.println("app exception");
}
}
}
class MQProducer implements Runnable {
private int counter = 0;
public void run() {
try {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(MQTest.DEFAULTUSER, MQTest.DEFAULTPASSWORD, MQTest.DEFAULTBROKERURL);
Connection connection = factory.createConnection();
// connection.start();
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(session.createQueue("testQueue"));
while (!Thread.interrupted()) {
TimeUnit.MILLISECONDS.sleep(1000);
System.out.println("before");
producer.send(session.createTextMessage("test message " + counter++));
System.out.println("after");
session.commit();
}
} catch (Exception e) {
System.out.println("producer exception");
}
}
}
class MQConsumer implements Runnable {
public void run() {
try {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(MQTest.DEFAULTUSER, MQTest.DEFAULTPASSWORD, MQTest.DEFAULTBROKERURL);
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(session.createQueue("testQueue"));
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println(textMessage.getText());
} catch (JMSException e) {
System.out.println("listener exception");
}
}
});
/*while (!Thread.interrupted()) {
Thread.sleep(1000);
System.out.println("test");
*//*Message receive = consumer.receive();
System.out.println(((TextMessage)receive).getText());*//*
}*/
} catch (Exception e) {
System.out.println("consumer exception");
}
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>maven</artifactId>
<groupId>com.placeholder</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>demo</artifactId>
<packaging>jar</packaging>
<name>demo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-examples -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>3.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.activemq/activemq-all -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client -->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.7.3</version>
</dependency>
<dependency>
<groupId>org.nanohttpd</groupId> <!-- <groupId>com.nanohttpd</groupId> for 2.1.0 and earlier -->
<artifactId>nanohttpd</artifactId>
<version>2.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.20</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
</dependencies>
</project>
<file_sep>package com.cooolin.javeweb.web.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
/**
* Created by l on 17-8-1.
*/
@WebFilter(value = "/*", asyncSupported = true)
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init EncodingFilter");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
chain.doFilter(request, response);
}
@Override
public void destroy() {
System.out.println("destroy EncodingFilter");
}
}
<file_sep>package com.placeholder.freemarker;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class TestFreemarker {
public static void main(String[] args) throws Exception {
// Create your Configuration instance, and specify if up to what FreeMarker
// version (here 2.3.22) do you want to apply the fixes that are not 100%
// backward-compatible. See the Configuration JavaDoc for details.
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
// Specify the source where the template files come from. Here I set a
// plain directory for it, but non-file-system sources are possible too:
URL url = TestFreemarker.class.getClassLoader().getResource(".");
cfg.setDirectoryForTemplateLoading(new File(url.toURI()));
// Set the preferred charset template files are stored in. UTF-8 is
// a good choice in most applications:
cfg.setDefaultEncoding("UTF-8");
// Sets how errors will appear.
// During web page *development* TemplateExceptionHandler.HTML_DEBUG_HANDLER is better.
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
Template template = cfg.getTemplate("a.ftl");
Map<String, Object> root = new HashMap<>();
/*
<h1>Welcome ${user}!</h1>
<p>Our latest product:
<a href="${latestProduct.url}">${latestProduct.name}</a>!
* */
root.put("user", "link");
Map<String, Object> latestProduct = new HashMap<>();
root.put("latestProduct", latestProduct);
latestProduct.put("url", "www.baidu.com");
latestProduct.put("name", "this is name");
template.process(root, new OutputStreamWriter(System.out));
}
}
|
d875949a1f9a8f62bc2b3a3f51ec679bbd20b3e0
|
[
"Java",
"Maven POM"
] | 30
|
Java
|
lllockkk/demo
|
95d89891914d5ce831da02a1a50d27a41ca65384
|
d9a987d96c70692c74fabe1f3e85dee6ad8c231c
|
refs/heads/master
|
<repo_name>vuvuzella/uni-comp3290-ass<file_sep>/test/p1/notes.txt
CD19 notes:
1. Missing string primitive type for variables
- this makes it not able to store string literals
- using 'input' keyword to ask for inputs but then, has not string literat
data type. can only process integers or reals
2. Functions
2.1. When using the input keyword to ask for inputs from the user, the
only way to make the inputted values persist outside the functions is to
declare a variable outside the function and change that from within the
function. This means that the variable must be declared first outside of
the function.
3. In the BNF representation, the <asgnstat> is defined as
<asgnstat> ::= <var><asgnop><bool>
which upon first inspection, you seem to only can assign booleans to
variables. however, when digging deeper into <bool> production, we can
trace:
<bool> -> <rel> -> <expr> -> <fact> -> <term> -> <exponent> ->
<var> | <reallit> | <intlit> | <fncall> | true | false
which is really confusing since in terms of the heirarchy of data types
when doing an assignment or combined assignment operation.
4. The main's function must require a local variable to declare, while any
defined function does not, even though these two constructs look and act very
identical
5. In the main, only integer, real and boolean local variables can be
declared. however, in a function definition, you can define array types as
well
6. When declaring arrays of struct types, it is difficult to say what the
default values of the fields are.
<file_sep>/src/main/java/comp3290/IntegerState.java
/*
* NumberState.java
* author: <NAME>
*
*
*/
package comp3290;
import java.io.BufferedReader;
import java.io.IOException;
public class IntegerState extends ScannerState {
public IntegerState(){}
public ScannerState handle(StateVariables shared) {
// Start state handling //
BufferedReader reader = shared.getReader();
String inputBuffer = shared.getInputBuffer();
ScannerState nextState = null;
int cur = 0;
try {
reader.mark(1);
cur = reader.read();
// if (this.isDelimiter(cur) ||
// this.isSpace(cur) ||
// this.isNewline(cur) ||
// this.isAlphabet(cur)) {
if (!this.isNumber(cur)) {
if (cur == ScannerState.DOT) {
// move to float state
// inputBuffer += (char)cur;
// shared.setInputBuffer(inputBuffer);
// shared.incColNo();
// Pass handling to float
reader.reset();
nextState = new FloatState();
} else {
// create a number token
reader.reset();
int colNo = shared.getColNo() - inputBuffer.length();
shared.appendProgList(inputBuffer);
shared.setToken(new Token(Token.TILIT,
shared.getLineNo(),
colNo,
inputBuffer));
shared.setSuccess(true);
nextState = new InitialState();
}
} else {
// Continue consuming input
// nextState is Integer
inputBuffer += (char)cur;
shared.incColNo();
shared.setInputBuffer(inputBuffer);
nextState = this;
}
} catch (IOException e) {
System.out.println("Error in " + this.getClass().toString());
}
// End state handling //
return nextState;
}
}
<file_sep>/src/main/java/comp3290/UndefinedState.java
/*
* UndefinedState.java
* author: <NAME>
*
*
*/
package comp3290;
import java.io.BufferedReader;
import java.io.IOException;
public class UndefinedState extends ScannerState {
public UndefinedState() {}
public ScannerState handle(StateVariables shared) {
// Start state handling //
BufferedReader reader = shared.getReader();
String inputBuffer = shared.getInputBuffer();
ScannerState nextState = null;
int cur = 0;
try {
reader.mark(1);
cur = reader.read();
if (!this.isSpace(cur) &&
!this.isNewline(cur) &&
!this.isNumber(cur) &&
!this.isAlphabet(cur) &&
!this.isDelimiter(cur) &&
!this.isComment(cur, 1, reader) &&
cur != EOF) {
inputBuffer += (char) cur;
shared.setInputBuffer(inputBuffer);
shared.incColNo();
nextState = this;
} else if (cur == EXCLAMATION) {
// look forward
reader.reset();
reader.mark(2);
cur = reader.read();
int forward = reader.read();
reader.reset();
reader.mark(1);
// Special case to catch != operator
if (forward == EQUALS) {
// valid token found, move out of undefined
// let InitialState route to Delimiter state to get !=
int colStartNo = shared.getColNo()
- inputBuffer.length();
shared.appendProgList(inputBuffer);
shared.setToken(new Token(Token.TUNDF,
shared.getLineNo(),
colStartNo,
inputBuffer));
shared.setSuccess(true);
nextState = new InitialState();
} else {
// not !=, cur is invalid
cur = reader.read();
inputBuffer += (char) cur;
shared.setInputBuffer(inputBuffer);
shared.incColNo();
nextState = this;
}
} else {
reader.reset();
int colStartNo = shared.getColNo() - inputBuffer.length();
shared.appendProgList(inputBuffer);
shared.setToken(new Token(Token.TUNDF,
shared.getLineNo(),
colStartNo,
inputBuffer));
shared.setSuccess(true);
nextState = new InitialState();
}
} catch (IOException e) {
System.out.println("Error in class: " + this.getClass().toString());
}
return nextState;
}
}
<file_sep>/src/main/java/comp3290/StringState.java
/*
* StringState.java
* author: <NAME>
*
*
*/
package comp3290;
import java.io.BufferedReader;
import java.io.IOException;
public class StringState extends ScannerState {
private boolean prevStringState;
public StringState(){
this.prevStringState = false;
}
public ScannerState handle(StateVariables shared) {
// Start state handling //
BufferedReader reader = shared.getReader();
String inputBuffer = shared.getInputBuffer();
ScannerState nextState = null;
int cur = 0;
try {
if (!this.prevStringState) {
// handle the openning quotes
reader.mark(1);
cur = reader.read();
inputBuffer += (char) cur;
shared.incColNo();
this.prevStringState = true;
}
reader.mark(1);
cur = reader.read();
if (cur != NEWLINE &&
cur != QUOTE &&
cur != CARRIAGE_RETURN) {
// process the string
inputBuffer += (char) cur;
shared.setInputBuffer(inputBuffer);
shared.incColNo();
nextState = this;
} else {
if (cur == QUOTE) {
// if quote, close the string TSTRG
// inputBuffer += (char) cur;
// Remove the beginning quote of the string
inputBuffer = inputBuffer.substring(1);
shared.incColNo();
int colStartNo = shared.getColNo() - inputBuffer.length();
shared.setToken(new Token(Token.TSTRG,
shared.getLineNo(),
colStartNo,
inputBuffer));
shared.setSuccess(true);
shared.appendProgList(inputBuffer);
nextState = new InitialState();
} else {
// if newline or carriage return, TUNDF
// inputBuffer += (char) cur;
shared.incColNo();
int colStartNo = shared.getColNo() - inputBuffer.length();
shared.appendProgList(inputBuffer);
shared.setToken(new Token(Token.TUNDF,
shared.getLineNo(),
colStartNo,
inputBuffer));
shared.resetColNo();
shared.incLineNo();
shared.setSuccess(true);
nextState = new InitialState();
}
}
} catch (IOException e) {
}
// End state handling //
return nextState;
}
}
<file_sep>/src/main/java/comp3290/CD19Scanner.java
/*
* CD19Scanner.java
* author: <NAME>
*
*/
package comp3290;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
public class CD19Scanner {
private File inputFile;
private BufferedReader reader; // shared variable
private int lineNumber; // shared variable
private int colNumber; // shared variable
private STATE currentState; // For Deprecation
private ScannerState state;
// Different states the scanner can be in
// TODO: eveyrtime the call to getNextToken finishes, scanner should be in
// INITIAL state
// CD19Scanner is the context state
private enum STATE {
INITIAL, NUMBER, ALPHABET, COMMENT, DELIMITER
};
private StateVariables shared;
public CD19Scanner(String inputFile)
throws FileNotFoundException, IOException {
this.inputFile = new File(inputFile);
this.currentState = STATE.INITIAL;
// Create new shared variables object
this.shared = new StateVariables();
this.state = new InitialState();
if (!this.inputFile.exists()) {
throw new FileNotFoundException();
}
try {
// this.reader = this.getNewReader(this.inputFile);
this.shared.setReader(new BufferedReader(new FileReader(this.inputFile)));
this.shared.setProgramListing(new ProgramListing(this.inputFile.toString(),
shared.getLineNo()));
} catch (IOException e) {
throw e;
}
}
public Token getNextToken() {
// Scan the reader to get all the lexems and store to buffered input
// If a delimiter is received, compare the buffered input to one of
// the tokens
// If it matched the token, create a token
// return the token
Token token = null;
boolean isSuccess = false;
if (this.shared.isEof()) {
// end of state reached
// do not process
System.out.println("EOF reached");
return null;
} else {
while (!shared.isEof() &&
token == null) {
// execute state's handle function
this.state = this.state.handle(this.shared);
token = this.shared.getToken();
}
// process results
isSuccess = this.shared.isSuccess();
this.shared.resetVariables();
if (!isSuccess) {
// print error message here
// stop iteration
System.out.println("Error occurred during state handle.");
}
}
return token;
}
public boolean hasNext() {
return !this.shared.isEof();
}
public void close() {
shared.close();
}
public ProgramListing getListing() {return shared.getListing();}
}
|
cf7314521cdda8a2350a2499806ede284d5df311
|
[
"Java",
"Text"
] | 5
|
Text
|
vuvuzella/uni-comp3290-ass
|
c97bd7fd390cf7edd08bbfecfe186d553daab23f
|
373098db4c4479449f1c8cd9c1adb16259ff55cd
|
refs/heads/master
|
<file_sep>import $ from "jquery";
function jQueryify(){
$(document).ready(function() {
$('#timeline-filterables').find('a').on('click', function() {
$('#timeline-filterables').find('a').removeClass('clickedOn');
$(this).addClass('clickedOn');
});
});
};
export default jQueryify;
<file_sep>import React from 'react';
class RepInfoDisplay extends React.Component {
constructor() {
super();
}
render() {
let {fullName, district, web} = this.props.repDisplay
return (
<div className="materialize" id="rep-info">
<ul id="repInfoUL" className="collection row">
<li className="collection-item avatar col s4">
<span className="title">Your State Senator</span>
<p>{fullName}</p>
</li>
<li className="collection-item avatar col s4">
<span className="title">District</span>
<p>{district}</p>
</li>
<li className="collection-item avatar col s4">
<p id="senatorLink"><a target="_blank" href={web}>{fullName}'s Website</a></p>
</li>
</ul>
</div>
// <div id="rep-info">
// <ul>
// <li>Your Senator: {fullName}</li>
// <li>Your District: {district}</li>
// <li><a href={web}>Your Senator's Website</a></li>
// </ul>
// </div>
)
}
}
export default RepInfoDisplay;
<file_sep>import React from 'react';
import setupListeners from './timeline_fcns.js';
import $ from "jquery";
import {IScroll} from 'fullpage.js';
import fullpage from 'fullpage.js';
class Bill extends React.Component {
constructor() {
super();
}
componentDidMount() {
// $.fn.fullpage.reBuild();
// $.fn.fullpage.setAutoScrolling(false);
// $.fn.fullpage.setFitToSection(false);
let {year, title, yay, nay, repDecision, summary} = this.props.data
Chart.defaults.global.defaultFontColor = "white";
var data = {
labels: [
"Yay",
"Nay"
],
datasets: [
{
data: [yay, nay],
backgroundColor: [
"#D3D3D3",
"#2a2a2a"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB"
]
}
]
};
let pieChart = new Chart(this.refs.chart, {
type: "pie",
data: data
});
}
shouldComponentUpdate(newProps) {
var othaOthaSupaKey = this.props.othaSupaKey + 1000;
var canvasHolderId = "#"+othaOthaSupaKey;
// $(canvasHolderId).find('canvas').remove();
$(canvasHolderId).find('iframe').remove();
//
//
//
return true;
}
componentWillReceiveProps(newProps) {
}
componentDidUpdate(){
var othaOthaSupaKey = this.props.othaSupaKey + 1000;
var realKey = othaOthaSupaKey + 1000;
var canvasHolderId = "#"+othaOthaSupaKey;
var freshCanvas = "<canvas ref='chart' id="+this.props.supaKey+" style='display: block; width: 0px; height: 0px;' width='0' height='0'>";
// $(canvasHolderId).append(freshCanvas);
let {year, title, yay, nay, repDecision, summary} = this.props.data
Chart.defaults.global.defaultFontColor = "white";
var data = {
labels: [
"Yay",
"Nay"
],
datasets: [
{
data: [yay, nay],
backgroundColor: [
"#D3D3D3",
"#2a2a2a"
]
}
]
};
var canvasTag = document.createElement("canvas")
canvasTag.setAttribute("ref", "chart")
canvasTag.setAttribute("id", this.props.supaKey)
let pieChart = new Chart(this.refs.chart, {
type: "pie",
data: data
});
}
//
// componentWillUpdate() {
// $.fn.fullpage.reBuild();
//
//
//
// let {year, title, yay, nay, repDecision, summary} = this.props.data
// Chart.defaults.global.defaultFontColor = "white";
//
// var data = {
// labels: [
// "Yay",
// "Nay"
// ],
// datasets: [
// {
// data: [yay, nay],
// backgroundColor: [
// "red",
// "blue"
// ],
// hoverBackgroundColor: [
// "#FF6384",
// "#36A2EB"
// ]
// }
// ]
// };
//
// let pieChart = new Chart(this.refs.chart, {
// type: "pie",
// data: data
// });
// return false;
// }
render() {
let {year, session, title, yay, nay, senatorDecision, summary, status, date, billId} = this.props.data
let {supaKey, othaSupaKey} = this.props
let othaOthaSupaKey = this.props.othaSupaKey + 1000
let realKey = othaOthaSupaKey + 1000;
return(
<li id={othaSupaKey}>
<div className="big-box">
<p id="title">"{title}"</p>
<hr/>
<p id ="decision"><span id="billInfo">YOUR SENATOR'S DECISION</span>: {senatorDecision}</p>
<p><span id="billInfo">STATUS</span>: {status} as of {date}</p>
<div className="hover-box">
<br></br>
<p id={othaOthaSupaKey} ref="holder"><canvas ref="chart" id={realKey}></canvas></p>
<br></br>
<p><a target="_blank" href={"https://www.nysenate.gov/legislation/bills/" + session + "/" + billId}>bill webpage</a> | <a target="_blank" href={"http://legislation.nysenate.gov/api/3/bills/" + session + "/" + billId + ".pdf/?key=<KEY>"}>bill pdf</a></p>
</div>
</div>
</li>
)
}
}
export default Bill;
<file_sep>import React from 'react';
class AddressForm extends React.Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
this.formStyle = this.formStyle.bind(this);
}
formStyle() {
if (this.props.hideIt) {
return {
display: ""
}
} else {
return {
display: "none"
}
}
}
handleSubmit(e) {
e.preventDefault();
if (this.refs.address.value.length > 0 && this.refs.city.value.length > 0) {
var fullAddress = this.refs.address.value + ' ' + this.refs.city.value + ' ' + this.refs.zip.value
this.refs.address.value = ''
this.refs.city.value = ''
this.refs.zip.value = ''
this.props.getAddress(fullAddress)
}
else { return null }
}
render() {
return(
<div className="materialize">
<div id="main-form" className="row" style={this.formStyle()}>
<form onSubmit={this.handleSubmit} className="col s12" autoComplete="off">
<div className="row">
<div className="input-field col s5">
<input name="address" ref="address" id="address" type="text" className="validate" />
<label htmlFor="address">Address</label>
</div>
<div className="input-field col s5">
<input name="city" ref="city" id="city" type="text" className="validate" />
<label htmlFor="city">City</label>
</div>
<div className="input-field col s2">
<input name="zip" ref="zip" id="zip" type="text" className="validate" />
<label htmlFor="zip">Zip</label>
</div>
</div>
<button id="supaButton" className="btn waves-effect waves-light" type="submit" name="action">Find My State Senator
<i className="material-icons right">send</i>
</button>
</form>
</div>
</div>
)
}
}
export default AddressForm;
<file_sep># state-matters-js
##Contributors:
* [<NAME>](https://github.com/jackfeely)
* [<NAME>](https://github.com/foggy1) (Project Lead)
* [<NAME>](https://github.com/jmarsh433)
* [<NAME>](https://github.com/soreasy)
If you put **any** barriers between the average person and political information, they generally won't try to cross them. And who can blame them? People are busy: as Locke aptly pointed out hundreds of years ago, the main reason we need government is because it would be incredibly inconvenient to oversee the contents of both our private lives and all public affairs. That's the beauty of a representative democracy.
But if a person wants to be an informed voter, it shouldn't be so hard.
State Matters is a React.js project built in Node.js that allows NY residents to input their address, learn who their state senator is, and immediately see how that senator has been voting on the year's most contentious bills to date. Users can also see what kinds of bills their representative has been sponsoring, the status of those bills, and all of this can be filtered by key words that interest the voter.
State Matters uses NY's [Open Legislation API](https://github.com/nysenate/OpenLegislation), the Google Maps API for basic geocoding, and utlizes libraries like [Fullpage.js](https://github.com/alvarotrigo/fullPage.js/) and Materialize for its style and feel.
##Stretch Goals
* Include Assembly persons
* Notify users of upcoming elections
|
dd7ede3d5dd4b39ac72284a0b2851d01527129b4
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
nyc-wolves-2016/state-matters-js
|
b7cd89f11d60a4f4aa02676261f058b647626589
|
573fbbe422e52c62ddb863f7191ea5489fe9b741
|
refs/heads/master
|
<file_sep>package com.sachinhandiekar.examples.gatein.wsrp;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* @author <NAME>
*/
public class DOMUtils {
static Element createElement(String namespaceURI, String name) {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
try {
final DocumentBuilder builder = builderFactory.newDocumentBuilder();
final Document document = builder.newDocument();
return document.createElementNS(namespaceURI, name);
} catch (ParserConfigurationException e) {
throw new RuntimeException("Couldn't get a DocumentBuilder", e);
}
}
static Element createElement(String name) {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
try {
final DocumentBuilder builder = builderFactory.newDocumentBuilder();
final Document document = builder.newDocument();
return document.createElement(name);
} catch (ParserConfigurationException e) {
throw new RuntimeException("Couldn't get a DocumentBuilder", e);
}
}
static Node addChild(Node parent, String namespaceURI, String childName) {
final Element child = parent.getOwnerDocument().createElementNS(namespaceURI, childName);
return parent.appendChild(child);
}
static Node addChild(Node parent, String childName) {
final Element child = parent.getOwnerDocument().createElement(childName);
return parent.appendChild(child);
}
}<file_sep># gatein-wsrp-examples
Gatein WSRP Examples
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sachinhandiekar.examples.gatein</groupId>
<artifactId>InvocationHandlerDelegate</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<common-logging.version>2.1.1.Final-redhat-2</common-logging.version>
<wsrp-integration-api.version>2.2.11.Final-redhat-3</wsrp-integration-api.version>
</properties>
<dependencies>
<dependency>
<groupId>org.gatein.common</groupId>
<artifactId>common-logging</artifactId>
<version>${common-logging.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gatein.wsrp</groupId>
<artifactId>wsrp-integration-api</artifactId>
<version>${wsrp-integration-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project><file_sep>package com.sachinhandiekar.examples.gatein.wsrp;
import org.gatein.pc.api.invocation.PortletInvocation;
import org.gatein.pc.api.invocation.RenderInvocation;
import org.gatein.pc.api.invocation.response.PortletInvocationResponse;
import org.gatein.wsrp.api.extensions.ExtensionAccess;
import org.gatein.wsrp.api.extensions.InvocationHandlerDelegate;
import org.gatein.wsrp.api.extensions.UnmarshalledExtension;
import org.oasis.wsrp.v2.MarkupParams;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.logging.Logger;
/**
* @author <NAME>
*/
public class CustomProducerInvocationHandlerDelegate extends InvocationHandlerDelegate {
private static final Logger logger = Logger.getLogger(CustomProducerInvocationHandlerDelegate.class.getName());
@Override
public void processInvocation(PortletInvocation invocation) {
if (invocation instanceof RenderInvocation) {
final List<UnmarshalledExtension> requestExtensions = ExtensionAccess.getProducerExtensionAccessor().getRequestExtensionsFor(MarkupParams.class);
if (!requestExtensions.isEmpty()) {
final UnmarshalledExtension unmarshalledExtension = requestExtensions.get(0);
if (unmarshalledExtension.isElement()) {
final Element element = (Element) unmarshalledExtension.getValue();
NodeList nodeList = element.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
String nodeKey = node.getNodeName();
String nodeValue = node.getTextContent();
logger.info("Node Key : " + nodeKey);
logger.info("Node Value: " + nodeValue);
// Get the HttpServletRequest
HttpServletRequest httpServletRequest = invocation.getRequest();
// Set the attributes here
httpServletRequest.setAttribute(nodeKey, nodeValue);
}
}
}
}
}
}
@Override
public void processInvocationResponse(PortletInvocationResponse response, PortletInvocation invocation) {
// Do nothing
}
}
|
e4743e6a6ea5a12c8718f8525d58ed2a709edb6e
|
[
"Markdown",
"Java",
"Maven POM"
] | 4
|
Java
|
sachin-handiekar/gatein-wsrp-examples
|
544db3d4f3da380eec262e61db6034ae900b3b62
|
b3545b3cae4344750c80265aadc5d383a71bba4d
|
refs/heads/master
|
<file_sep>import React from "react";
import "./homepage.styles.scss";
import Directory from "../../components/directory/directory.component";
// functional component
// dont really need any lifecycle methods at this point nor need to store any state
const HomePage = () => (
<div className="homepage">
<Directory />
</div>
);
export default HomePage;
|
5afcba4c3dc70420f0a8b72916cb6ec998f212ca
|
[
"JavaScript"
] | 1
|
JavaScript
|
yuyuyes/crwn-clothing
|
c8e633d877ddcc2a6ab1addbf88cbfa2937f4e56
|
8f15c3a179ece62a56800401dcbca6372987678e
|
refs/heads/main
|
<file_sep>using Godot;
using Godododod.Entities;
using System;
public class Main : Node
{
private Player _Player;
private TileMap _Dung;
public override void _Ready()
{
_Player = new Player();
_Dung = (TileMap)GetNode("TileMap");
_Player.ConnectToNode(_Dung);
}
}
|
49ce36f6c4b3a410e65901b9c459978c7ba31c86
|
[
"C#"
] | 1
|
C#
|
SiP-G/Godododod
|
64d0885fc7fec9c8af0d91de593d915712ac2184
|
35e6441b60a53bb3f3388fe84281a21e19710a9e
|
refs/heads/master
|
<repo_name>Ly900/fellowship<file_sep>/fellowship.js
// <NAME>
var fellowship = {
hobbits: [
"<NAME>",
"Samwise '<NAME>",
"Meriadoc \"Merry\" Brandybuck",
"Peregrin 'Pippin' Took"
],
buddies: [
"<NAME>",
"Legolas",
"Gimli",
"Strider",
"Boromir"
],
lands: [
"The Shire", "Rivendell", "Mordor"
],
// create a section tag with an id of middle-earth
// add each land as an article tag
// inside each article tag include an h1 with the name of the land
// append middle-earth to your document body
makeMiddleEarth: function(lands) {
console.log(lands);
var section = document.createElement("section");
section.setAttribute("id", "middle-earth");
for (var i = 0; i < fellowship.lands.length; i++) {
var article = document.createElement("article");
var h1 = document.createElement("h1");
h1.textContent = fellowship.lands[i];
article.appendChild(h1);
document.getElementById("middle-earth").appendChild(article);
}
},
makeHobbits: function(hobbits) {
// display an unordered list of hobbits in the shire
// give each hobbit a class of hobbit
var ul = document.createElement("ul");
for (var i = 0; i < fellowship.hobbits.length; i++) {
var li = document.createElement("li");
li.setAttribute("class", "hobbit")
li.textContent = fellowship.hobbits[i];
ul.appendChild(li);
}
document.body.appendChild(ul);
var firstArt = document.querySelector("article")
firstArt.appendChild(ul);
},
keepItSecretKeepItSafe: function() {
// create a div with an id of 'the-ring'
// add the ring as a child of Frodo
var div = document.createElement("div");
div.id = "the-ring";
var frodo = document.getElementsByClassName("hobbit")[0];
frodo.appendChild(div);
},
makeBuddies: function(buddies) {
// create an aside tag
// display an unordered list of buddies in the aside
// insert your aside before rivendell
var aside = document.createElement("aside");
var ul = document.createElement("ul");
for (var i = 0; i < fellowship.buddies.length; i++) {
var li = document.createElement("li");
li.textContent = fellowship.buddies[i];
ul.appendChild(li);
}
aside.appendChild(ul);
var parentArticle = document.querySelectorAll("article")[1];
var rivendell = document.querySelectorAll("h1")[1];
rivendell.parentNode.insertBefore(aside, rivendell);
},
beautifulStranger: function() {
// change the buddy 'Strider' textnode to "Aragorn"
var strider = document.getElementsByTagName("ul")[1].childNodes[3];
strider.textContent = "Aragorn"
},
forgeTheFellowShip: function() {
// move the hobbits and the buddies to Rivendell
// create a new div called 'the-fellowship'
// add each hobbit and buddy one at a time to 'the-fellowship'
// after each character is added make an alert that they have joined your party
// did this to get the hobbits ul
var hobbits = document.querySelectorAll("ul")[0];
var rivendell = document.querySelectorAll("article")[1]
rivendell.appendChild(hobbits);
var buddies = document.querySelectorAll("ul")[0]
rivendell.appendChild(buddies);
var div = document.createElement("div");
div.id = "the-fellowship";
div.appendChild(document.createElement("ul"));
// did this to get the hobbits ul with li as 4 children.
var hobbits = document.querySelectorAll("ul")[0].childNodes;
for (var i = 0; i < hobbits.length + 1; i++) {
var i = 0;
alert(hobbits[i].textContent + " has joined your party.");
div.children[0].appendChild(hobbits[i]);
}
var buddies = document.querySelectorAll("ul")[1].childNodes;
for (var i = 0; i < buddies.length + 1; i++) {
var i = 0;
alert(buddies[i].textContent + " has joined your party.");
div.children[0].appendChild(buddies[i]);
}
// Alternate way:
// var hobbits = document.querySelectorAll("ul")[0].childNodes;
// while (hobbits.length > 0) {
// var hobbit = hobbits[0];
// alert(hobbit.textContent + " has joined your party.");
// div.children[0].appendChild(hobbit);
// }
} // ends forgeTheFellowship
} // ends fellowship object
fellowship.makeMiddleEarth(fellowship.lands);
fellowship.makeHobbits(fellowship.hobbits);
fellowship.keepItSecretKeepItSafe();
fellowship.makeBuddies(fellowship.buddies);
fellowship.beautifulStranger();
fellowship.forgeTheFellowShip();
// Why does makeMiddleEarth have parameters if they are not defined/used in the function?
// How do I get rid of the empty strings that are in the Mordor h1?
|
758845b6fbe8875730ec06182ecfaafe836c2b77
|
[
"JavaScript"
] | 1
|
JavaScript
|
Ly900/fellowship
|
96dd40b15b5d188aa08ad9f5144da5892019abd3
|
93f4d882a59c497d463d7aaf95c56bac538cb082
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.