通过网站按钮执行无限循环的python脚本不起作用

时间:2018-09-26 21:46:07

标签: javascript python html ajax

我想控制一个不断从传感器(while循环)收集数据的python脚本。我希望能够通过单击一个按钮来启动和停止该脚本。

我尝试了几种包含jQuery.ajax请求的解决方案,但可悲的是没有启动脚本。应该注意的是,我只想启动脚本,而不希望它有任何输出/返回值。

下面是我的代码,它不起作用。当我单击一个按钮时,什么也没有发生。我没有使用Python框架为该网站提供服务。我正在使用带有PHP,Apache的Raspberry Pi运行我自己的Web服务器。以下是仅启动脚本而不停止的代码。目前,我只想运行脚本。

<!DOCTYPE html>
<html>
<head> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" ></script>
<script>
    function goPython(){
        $.ajax({
         type: "POST", 
         url: 'alarmV1.py',
        }).done(function() {
         alert('DONE');;
        });
    }
</script>

</head>
<body>
  <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">
</body>
</html>

Python代码:

#!/usr/bin/python3
#!/usr/bin/env python

import smbus
import sys
import time
import MySQLdb
from time import sleep
from datetime import datetime
import math


fd = 0x20 #outputs
fd2 = 0x21 #inputs
dane = 0

state = ""

bus = smbus.SMBus(1)
bus.write_byte(fd2, 0xff)

while True:
   dane = bus.read_byte(fd2)

   if dane == 0xf8:
      print "OK"
      bus.write_byte(fd,0x03)
      time.sleep(0.4)
      state = 'Jest OK'
   elif dane == 0xf9:
       bus.write_byte(fd,0x00) #LED ON
       print "Kontaktron nr.1"
       time.sleep(0.4)
       bus.write_byte(fd,0x02) #LED OFF
       state = 'Kontaktron nr.1'
       time.sleep(0.4)
   elif dane == 0xfa:
       bus.write_byte(fd,0x00) #LED ON
       print "PIR"
       time.sleep(0.4)
       bus.write_byte(fd,0x02) #LED OFF
       state = 'Czujnik PIR nr.1'
       time.sleep(0.4)
   elif dane == 0xfc:
       bus.write_byte(fd,0x00) #LED ON
       print "Kontaktron nr.2"
       time.sleep(0.4)
       bus.write_byte(fd,0x02) #LED OFF
       state = 'Kontaktron nr.2'
       time.sleep(0.4)
   else:
       bus.write_byte(fd,0x00)
       print "more sensors"
       time.sleep(0.4)
       bus.write_byte(fd,0x02)
       state = 'Wiecej czujnikow'
       time.sleep(0.4)

   db = MySQLdb.connect("localhost", "adrian", "3kr39uvk", "AlarmBD")
   cursor = db.cursor()

   try:
       cursor.execute("INSERT INTO czujniki (id, nazwa_czujnika, data_czujnika) VALUE (NULL,%s,NOW())",[state])
       db.commit()
   except MySQLdb.Error, e:
       print "An error has occurred. %s" %e
   finally:
       cursor.close()
       db.close()

0 个答案:

没有答案