Advertisement
Guest User

Untitled

a guest
May 18th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.24 KB | None | 0 0
  1. from __future__ import print_function
  2. import sys
  3. import socket
  4. import os
  5. import thread
  6. import time
  7.  
  8. import imghdr
  9. import ConfigParser
  10. import argparse
  11. import subprocess
  12.  
  13. import pymysql
  14. import re
  15.  
  16. #parse argument (config file).
  17. parser = argparse.ArgumentParser()
  18. parser.add_argument("-c", "--conf", help="location of conf file", type=str)
  19. args = parser.parse_args()
  20.  
  21. #parse config file.
  22. Config = ConfigParser.ConfigParser()
  23. if args.conf:
  24. Config.read(args.conf)
  25.  
  26. else :
  27. print("no configure file")
  28. sys.exit()
  29.  
  30. Sadr = Config.get('Option', 'Sadr')
  31. Port = Config.get('Option', 'Port')
  32. LabScript = Config.get('Option', 'Lab_Script')
  33. ImgSaveDir = Config.get('Option', 'Received_Image_Directory')
  34. dbname = Config.get('Option', 'dbname')
  35. dbuname = Config.get('Option', 'dbuname')
  36. dbpass = Config.get('Option', 'dbpass')
  37.  
  38. #database.
  39. conn = pymysql.connect(host='localhost', user=dbuname, password=dbpass, db=dbname, charset = 'utf8')
  40. curs = conn.cursor()
  41.  
  42.  
  43. def insert(table,req):
  44. print('db insert')
  45. #print(req)
  46.  
  47. if(str(req[0])=='REGISTER'):
  48. colnval = '(uid,u_name,sex,birth_year,gid) values(\"'+str(req[1])+'\", \"'+str(req[2])+'\", \''+str(req[3])+'\', '+str(req[4])+', '+str(req[5])+')'
  49. elif(str(req[0])=='PICTURE'):
  50. ss=time.strftime("%Y%m%d")
  51. #print(ss)
  52. colnval = 'values('+ss+ ',\"'+str(req[2])+'\",\"' +str(req[4])+ '\",'+str(req[3]) +')'
  53.  
  54.  
  55. sql = "insert into " + table + " " + colnval
  56. print(sql)
  57.  
  58.  
  59. curs.execute(sql)
  60. conn.commit()
  61.  
  62. pass
  63.  
  64. def history_(connection, req):
  65. #date selecton function is not implemented.
  66.  
  67. sql = "select * from history where uid=\""+str(req[1])+ "\" order by date desc"
  68. curs.execute(sql)
  69. rows = curs.fetchall()
  70. #print(rows)
  71.  
  72. d=0
  73. xx=len(rows)
  74. #print(len(rows))
  75.  
  76. #print(rows[1])
  77. d=1
  78. date=str(unicode(rows[d][0]))
  79.  
  80. res=str()
  81.  
  82. while(d<xx):
  83.  
  84. date=str(unicode(rows[d][0]))
  85. uid=str(rows[d][1])
  86. foodname=str(rows[d][2])
  87. quant =float(rows[d][3])
  88. u='_'
  89.  
  90. sql = "select calorie,carbohydrate,protein,fat,fiber,vita_c,ca,na,fe from nutri_info where d_name=\""+foodname+"\""
  91. curs.execute(sql)
  92. rows2 = curs.fetchall()
  93. irows=list()
  94.  
  95. for i in rows2[0]:
  96. irows.append(float(i))
  97.  
  98.  
  99. mrows=list()
  100. for i in irows:
  101. mrows.append(i*float("{0:.2f}".format(quant)))
  102.  
  103. for i in mrows:
  104. #print(str(i), end='')
  105. #print('_', end='')
  106. res+= str(i) +'_'
  107.  
  108. res+='#'
  109. d+=1
  110.  
  111. slen = str(len(res)) +'_'
  112. #print('slen is ' + slen)
  113. connection.send(str.encode(slen))
  114. print(str.encode(connection.recv(100)))
  115.  
  116. sent =connection.send(str.encode(res))
  117. print(len(res))
  118. #print(res)
  119. print('history info sending done')
  120.  
  121. pass
  122.  
  123.  
  124. #TODO 1118: register, login, databse connection.
  125. def register_(connection, req):
  126. insert('member_info', req)
  127. sql= "select * from member_info"
  128. curs.execute(sql)
  129. rows = curs.fetchall()
  130.  
  131. for i in rows:
  132. print(i)
  133.  
  134. print('register : '+ str(req[1]) + ' success')
  135.  
  136. #sql = 'insert into member_info (uid,u_name,sex,birth_year,gid) vaules('
  137.  
  138. pass
  139.  
  140. def login_(connection, req):
  141. #nothing todo yet
  142.  
  143. uid = req[1]
  144. sql= "select uid from member_info where uid =\""+ str(uid) +"\""
  145. curs.execute(sql)
  146. rows = curs.fetchall()
  147.  
  148. if rows:
  149. print("login success")
  150. print('id : ' + str(req[1]))
  151. pass
  152. else:
  153. print("no such id " + str(req[1]))
  154.  
  155.  
  156.  
  157. def label_image(img, connection, req):
  158. #call lab_image.py
  159. print(LabScript + ' ' + img)
  160. batcmd = 'sudo python ' + LabScript + ' ' + img
  161. result = subprocess.check_output(batcmd, shell=True)
  162. print('--------------')
  163. print(result)
  164. res = result.split('(')[0]
  165. s = result.split('=')[1]
  166. s = s.split(')')[0]
  167. res += s
  168. res = res.replace(' ','-')
  169. food = res.split('-')[0]
  170.  
  171. print('Result is : ' +str(res))
  172. res = 'result_'+str(res)+'_'
  173. connection.send(str.encode(res))
  174. connection.close()
  175.  
  176. #bad coding.
  177. req[4]=food
  178.  
  179. insert("history",req)
  180.  
  181. pass
  182.  
  183. def picture_(connection,req):
  184. #make img file name.
  185. cn = str(connection).replace(' ','_')
  186. cn = cn.replace('<','')
  187. cn = cn.replace('>','')
  188. fname = ImgSaveDir + cn
  189. rlen =0
  190.  
  191. f=open(fname, 'wb+')
  192.  
  193. try:
  194. #print('come in pictrue')
  195. flen = int(req[1])
  196. print('flen is ' + str(flen))
  197.  
  198. while rlen < flen:
  199. data = connection.recv(1024)
  200.  
  201. if len(data):
  202. f.write(data)
  203. rlen+=len(data)
  204.  
  205. else:
  206. print(str(rlen))
  207. print('img save done ')
  208. except:
  209. e = sys.exc_info()[0]
  210. print(e)
  211.  
  212. finally:
  213. #print(str(rlen))
  214. #detect img file type, using imghdr.
  215. imgtype = imghdr.what(fname)
  216. for filename in os.listdir(ImgSaveDir):
  217. if filename.startswith(cn):
  218. os.rename(ImgSaveDir + filename, fname+'.'+ imgtype)
  219. fname = fname + '.' + imgtype
  220. print('file name is %s' %fname)
  221. f.close()
  222. #connection.close()
  223. #print('connection closed')
  224. thread.start_new_thread(label_image, (fname,connection, req, ))
  225.  
  226.  
  227. def app_handler(connection):
  228. #TODO 11/15 ##### howto Receive string message(?) connection.recv() to string so idendify request string. #######
  229. ##### implementation while loop for request parser ###########
  230. try:
  231.  
  232. connection.send(str.encode("OK_\n\n"))
  233.  
  234. req= str.decode(connection.recv(1024))
  235. print('\n'+req)
  236. req=req.split('_')
  237. rqn = req[0]
  238.  
  239. if(rqn=='REGISTER'):
  240. thread.start_new_thread(register_,(connection, req))
  241. pass
  242. elif(rqn=='LOGIN'):
  243. thread.start_new_thread(login_,(connection, req))
  244. pass
  245. elif(rqn=='PICTURE'):
  246. print('picture start')
  247. thread.start_new_thread(picture_,(connection, req))
  248. elif(rqn=='HISTORY'):
  249. print('history start')
  250. thread.start_new_thread(history_,(connection, req))
  251.  
  252. except:
  253. e = sys.exc_info()[0]
  254. print(e)
  255.  
  256. finally:
  257. pass
  258.  
  259. def rasp_login(connection, req):
  260. print(req)
  261.  
  262. uid = req[1]
  263. sql= "select gid from member_info where uid =\""+ str(uid) +"\""
  264. curs.execute(sql)
  265. rows = curs.fetchall()
  266.  
  267. if rows:
  268. print("login success")
  269. print('id : ' + str(req[1]))
  270. pass
  271. else:
  272. print("no such id " + str(req[1]))
  273.  
  274. return int(str(rows[0]))
  275.  
  276.  
  277. def rasp_history(connection, req, gid):
  278. #It may have error.
  279. #date selecton function is not implemented.
  280. #the amount of data is fixed in raspberyy program.
  281.  
  282. sql= "select uid from memeber_info where gid=\"" +str(gid) +"\""
  283. curs.execute(sql)
  284. rows2 = curs.fetchall()
  285. totmsg=''
  286.  
  287. for uid in rows2:
  288.  
  289. sql = "select * from history where uid=\""+str(uid) + "\" order by date desc"
  290. curs.execute(sql)
  291. rows = curs.fetchall()
  292. #print(rows)
  293.  
  294. d=0
  295. xx=len(rows)
  296.  
  297. d=1
  298. date=str(unicode(rows[d][0]))
  299.  
  300. res=str()
  301.  
  302. while(d<xx):
  303.  
  304. date=str(unicode(rows[d][0]))
  305. uid=str(rows[d][1])
  306. foodname=str(rows[d][2])
  307. quant =float(rows[d][3])
  308. u='_'
  309.  
  310. sql = "select calorie,carbohydrate,protein,fat,fiber,vita_c,ca,na,fe from nutri_info where d_name=\""+foodname+"\""
  311. curs.execute(sql)
  312. rows2 = curs.fetchall()
  313. irows=list()
  314.  
  315. for i in rows2[0]:
  316. irows.append(float(i))
  317.  
  318.  
  319. mrows=list()
  320. for i in irows:
  321. mrows.append(i*float("{0:.2f}".format(quant)))
  322.  
  323. for i in mrows:
  324. #print(str(i), end='')
  325. #print('_', end='')
  326. res+= str(i) +'_'
  327.  
  328. #rasp don't need this '#'' and length of msg.
  329. #res+='#'
  330. d+=1
  331.  
  332. totmsg = totmsg + res
  333.  
  334. sent =connection.send(str.encode(totmsg))
  335. #print(len(res))
  336. #print(sent)
  337. print('history info sending done')
  338.  
  339. pass
  340.  
  341.  
  342. def rasp_handler(connection, req):
  343.  
  344. #After connection firtst req is treated specially. so recv is in finally statement.
  345. #Message type is RASP_LOGIN_ID_
  346. #RASP_HISTORY_ID_
  347.  
  348. gid=0
  349.  
  350. while connection:
  351. try:
  352.  
  353. connection.send(str.encode("OK_"))
  354.  
  355. print(req)
  356. req=req.split('_')
  357. rqn = req[0]
  358.  
  359. if(rqn=='LOGIN'):
  360. print('rasp login')
  361. gid = rasp_login(connection, req)
  362. if(rqn=='HISTORY'):
  363. print('rasp history')
  364. rasp_history(connection, req, gid)
  365. pass
  366.  
  367. except:
  368. pass
  369.  
  370. finally:
  371. req= str.decode(connection.recv(1024))
  372. req = req.split('_')[1]
  373.  
  374. 1
  375. def main():
  376. #create a tcp/ip socket.
  377. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  378.  
  379.  
  380. #bind the socket to the port
  381. s_addr = (Sadr, int(Port))
  382. print('start up on %s port %s' %s_addr)
  383. sock.bind(s_addr)
  384. sock.listen(1)
  385.  
  386. flag=1
  387.  
  388. while True:
  389. if(flag==1):
  390. print('wating for connection')
  391. connection, c_addr = sock.accept()
  392. if(flag==1):
  393. print('connection from %s', c_addr)
  394.  
  395. cl = str.decode(connection.recv(1024))
  396. cl = str(cl)
  397. cl2=cl.split('_')[0]
  398. cl3 = cl.split('_')[1]
  399.  
  400. if(cl2=='APP'):
  401. thread.start_new_thread(app_handler,(connection, ))
  402. if(flag==1):
  403. print('app started')
  404. flag=0
  405. elif(cl2=='RASP'):
  406. print('rasp came')
  407. thread.start_new_thread(rasp_handler,(connection, cl3, ))
  408.  
  409. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement