From 4a7ebc447b0ec715fa7a50d58c654a258876fb21 Mon Sep 17 00:00:00 2001 From: splasky Date: Thu, 31 May 2018 10:39:19 +0800 Subject: [PATCH] Fix merege error --- src/python/package/da.py | 754 +++++++++------------------------------ src/python/server.py | 356 ++++-------------- 2 files changed, 242 insertions(+), 868 deletions(-) diff --git a/src/python/package/da.py b/src/python/package/da.py index 3de9352..4810084 100644 --- a/src/python/package/da.py +++ b/src/python/package/da.py @@ -1,14 +1,12 @@ -<<<<<<< HEAD -#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 -# Last modified: 2016-11-30 20:57:38 +# Last modified: 2018-05-31 10:39:01 import sys import time import json import os -import send +from . import send import math import subprocess import re @@ -18,13 +16,12 @@ from abc import ABCMeta, abstractmethod from package.debug import PrintException - # Third party -import Adafruit_TMP.TMP006 as TMP006 import MySQLdb -import DHT11 -from scp import SCPClient # not use +from package.dht11 import libDHT11 +from package import TMP006 from adxl345 import ADXL345 +# import from third party lib sys.path.append("/usr/lib/python2.7/site-packages/") from printrun.printcore import printcore from printrun import gcoder @@ -34,7 +31,7 @@ class CommandSwitchTableProto(object): metaclass__ = ABCMeta - def __init__(self): + def __init__(self, *args, **kwargs): self.task = { "connect": self.connect, "disconnect": self.disconnect, @@ -112,72 +109,96 @@ def Default(self): class PrintCore(object): + Port = '/dev/ttyUSB0' + Baud = 250000 - def __init__(self, Port='/dev/ttyUSB0', Baud=250000): - self.printcoreHandler = printcore(port=Port, baud=Baud) + def __init__(self, Port=None, Baud=None): + self.printcoreHandler = printcore() + self.logl = 0 + self.temp = 0 + + def connect(self, Port='/dev/ttyUSB0', Baud=250000): try: - self.printcoreHandler.logl - except: + self.printcoreHandler.connect(port=Port, baud=Baud) + # must wait for printcore connect success + time.sleep(3) setattr(self.printcoreHandler, 'logl', 0) + except: + PrintException() def disconnect(self): - self.printcoreHandler.disconnect() - print "py:disconnect..." + try: + self.printcoreHandler.disconnect() + return True + except: + PrintException() + return False + + def is_printing(self): + return self.printcoreHandler.printing def reset(self): self.printcoreHandler.reset() - print'py:reset print' + print('py:reset print') + return True def pause(self): self.printcoreHandler.pause() - print 'py:pause print' + print('py:pause print') + return True def resume(self): self.printcoreHandler.resume() - print 'py:resume print' + print('py:resume print') + return True def cancel(self): self.printcoreHandler.cancelprint() self.printcoreHandler.send_now("M104 S0") # cool dowm self.printcoreHandler.send_now("G28") # home self.printcoreHandler.send_now("M84") # stepperoff - print "py:cancel print" - time.sleep(3) + print("py:cancel print") + return True def cooldown(self): self.printcoreHandler.send_now("M104 S0") - print 'py:cooldown' + print('py:cooldown') + return True def home(self): self.printcoreHandler.send_now("G28") - print 'py:home' + print('py:home') + return True def send_now(self, command): try: self.printcoreHandler.send_now(command) print("send command success") + return True except: print("py:send command failed") return False def startprint(self, file): try: - print 'start print...' + print('start print...') gcode = [i.strip() for i in open(file)] gcode = gcoder.LightGCode(gcode) self.printcoreHandler.startprint(gcode) print("py:print") + return True except: - self.printcoreHandler.cancelprint() - self.printcoreHandler.send_now("M104 S0") # cool dowm - self.printcoreHandler.send_now("G28") # home - self.printcoreHandler.send_now("M84") # stepperoff + self.cancel() PrintException() return False def stepperoff(self): self.printcoreHandler.send_now("M84") - print 'py:stepper off' + print('py:stepper off') + return True + + def isPaused(self): + return self.printcoreHandler.paused def printer_status(self): """get printer status into json file @@ -186,13 +207,18 @@ def printer_status(self): :return: return json string """ - data = dict() + data = {} data["clear"] = self.printcoreHandler.clear data["isprinting"] = self.printcoreHandler.printing data["online"] = self.printcoreHandler.online data["baud"] = self.printcoreHandler.baud data["port"] = self.printcoreHandler.port - data["position"] = self.getPosition() + try: + data["IR_temperature"] = self.headtemp() + data["position"] = self.getPosition() + except: + pass + data["ispause"] = self.isPaused() return data def gettemp(self): @@ -204,24 +230,18 @@ def gettemp(self): setattr(self, 'logl', 0) setattr(self, 'temp', 0) - htemp = None - - while htemp is None: - if(self.printcoreHandler.online is False): - break - for n in range(self.printcoreHandler.logl, len(self.printcoreHandler.log)): - line = self.printcoreHandler.log[n] - if 'T:' in line: - te = line.split('T:')[1] - htemp = float(te.split("/")[0].strip()) - setattr(self, 'temp', htemp) - self.printcoreHandler.logl = len(self.printcoreHandler.log) - break - self.printcoreHandler.send_now("M105") - time.sleep(1) - # logging.debug("deque:{0}".format(str(self.printcoreHandler.log))) - - return htemp + if(self.printcoreHandler.online is False): + return None + for n in range(self.printcoreHandler.logl, len(self.printcoreHandler.log)): + line = self.printcoreHandler.log[n] + if 'T:' in line: + te = line.split('T:')[1] + htemp = float(te.split("/")[0].strip()) + setattr(self, 'temp', htemp) + self.printcoreHandler.logl = len(self.printcoreHandler.log) + self.printcoreHandler.send_now("M105") + return htemp + return None def headtemp(self): try: @@ -237,588 +257,154 @@ def getPosition(self): time.sleep(1) for n in range(self.printcoreHandler.logl, len(self.printcoreHandler.log)): line = self.printcoreHandler.log[n] - if("X:"in line): # may be mistake - logging.debug("Position:{0}".format(line)) - self.printcoreHandler.logl = len(self.printcoreHandler.log) + if("X:"in line): return line.strip() except: - PrintException() - logging.debug("in GetPosition {0}".format(line)) + logging.debug("Printcore:get position error.") return '' -def create_json_file(data): +def create_json_file(path, data): """write a json file to path + :path: data to be store :data: data to be send :return: write success return file path else None """ try: beSended = json.dumps(data) - fp = '/tmp/printer.json' - with open(os.path.abspath(fp), 'w') as file: + with open(os.path.join(path), 'w') as file: file.write(beSended) - return fp - except Exception, e: - print(e.args) - return None - - -def DHT11_temp(): - # have to use DHT11.Init_WiringPi() first - checksum = 0 - while(checksum is 0): - humidity, humidityfloat, temperature, temperaturefloat, checksum = DHT11.read_DHT11() - - logging.debug("checksum :{0}".format(checksum)) - if checksum == 0: - return None - else: - dict = {"humidity": humidity, "humidityfloat": humidityfloat, - "temperature": temperature, "temperaturefloat": temperaturefloat} - return dict + except Exception as e: + print((e.args)) -def get_G_sensor(): - adxl345 = ADXL345() - axes = adxl345.getAxes(True) +class sensors(object): - g_x = (axes['x']) - g_y = (axes['y']) - g_z = (axes['z']) - - return g_x, g_y, g_z - - -def IR_temp(): - # IR Temperature: - sensor = TMP006.TMP006() - sensor.begin() - obj_temp = sensor.readObjTempC() - die_temp = sensor.readDieTempC() - - return obj_temp - - -def get_Sensors_data(data={}): - - dict = DHT11_temp() - if dict is not None: - data["humidity"] = dict["humidity"] - data["temp"] = dict["temperature"] - else: - return None + def __init__(self): + self.humidity = 0 + self.temperature = 0 - (g_x, g_y, g_z) = get_G_sensor() - data["g_x"] = g_x - data["g_y"] = g_y - data["g_z"] = g_z + def get_current_time(self): + return str(datetime.datetime.now()) - logging.debug("Temperature: {0} C".format(data["temp"])) - logging.debug("Humidity: {0}%%".format(data["humidity"])) + def DHT11_temp(self): + try: + # have to use libDHT11.Init_WiringPi() first + checksum = 0 + # while checksum is not 0: + humidity, humidityfloat, temperature, temperaturefloat, checksum = libDHT11.read_DHT11() - logging.debug(" x = {0}".format((g_x))) - logging.debug(" y = {0}".format((g_y))) - logging.debug(" z = {0}".format((g_z))) + while True: + if checksum is not 0: + break + else: + humidity, humidityfloat, temperature, temperaturefloat, checksum = libDHT11.read_DHT11() - return data + data = {"humidity": humidity, "humidityfloat": humidityfloat, + "temperature": temperature, "temperaturefloat": temperaturefloat} + if(humidity + temperature != checksum): + data["humidity"] = self.humidity + data["temperature"] = self.temperature -def SQLOperate(db, cursor, sqlcommand): - AVG = 'UPDATE static set avg=(SELECT AVG(IR_temperature) FROM env_data)' - static = 'select * from static' + self.humidity = data["humidity"] + self.temperature = data["temperature"] - # Execute the SQL command + return data + except: + PrintException() + return {} - n = 1000 + def get_G_sensor(self): - cursor.execute(sqlcommand) - db.commit() - cursor.execute(AVG) - db.commit() + try: + adxl345 = ADXL345() + axes = adxl345.getAxes(True) - # Commit your changes in the database - cursor.execute(static) - each_row_of_static = cursor.fetchall() + g_x = (axes['x']) + g_y = (axes['y']) + g_z = (axes['z']) - for row in each_row_of_static: + return g_x, g_y, g_z + except: + PrintException() + return {} - x = row[0] + def IR_temp(self): + try: + # IR Temperature: + sensor = TMP006.TMP006() + sensor.begin() + obj_temp = sensor.readObjTempC() + die_temp = sensor.readDieTempC() + return obj_temp + except: + PrintException() + return {} - std = row[1] + def get_Sensors_data(self): + try: + data = self.DHT11_temp() + (data["g_x"], data["g_y"], data["g_z"]) = self.get_G_sensor() + data["time"] = self.get_current_time() - ans = x + 1.96 * std / math.sqrt(n) - low = x - 1.96 * std / math.sqrt(n) + return data + except: + PrintException() + return {} - sqlforcheck = 'UPDATE static set check_value_high={} '.format(ans) - sqllowcheck = 'UPDATE static set check_value_low={} '.format(low) - cursor.execute(sqlforcheck) - cursor.execute(sqllowcheck) - db.commit() +class SqlManager(object): -def Send_Sensors(host="163.17.135.169", user="pi", password="raspberry", database="libRaspberry", port=3306, data={}): - try: - db = MySQLdb.connect(host, user, password, database, port) - cursor = db.cursor() - # Run the DHT program to get the humidity and temperature readings! + def __init__(self, host, user, password, database, port): + self.host = host + self.user = user + self.password = password + self.database = database + self.port = port + self.db_hander = MySQLdb.connect(host, user, password, database, port) + self.cursor = self.db_hander.cursor() - sql = "Insert into env_data(humidity,temperature,x_axis,y_axis,z_axis,IR_temperature) values({},{},{},{},{},{})".format( - data["humidity"], - data["temp"], - data["g_x"], - data["g_y"], - data["g_z"], - float(data["IR_temperature"]) - ) + def __del__(self): + self.cursor.close() + self.db_hander.close() + logging.debug("close SqlManager success") - # Prepare SQL query to INSERT a record into the database. + def SQLOperate(self, sqlcommand): + try: + # Execute the SQL command + self.cursor.execute(sqlcommand) + self.db_hander.commit() + except: + PrintException() + def Send_Sensors(self, data={}): try: - SQLOperate(db, cursor, sql) + # Prepare SQL query to INSERT a record into the database. + sql = "Insert into env_data(humidity,temperature,x_axis,y_axis,z_axis,IR_temperature) values({},{},{},{},{},{})".format( + data["humidity"], + data["temp"], + data["g_x"], + data["g_y"], + data["g_z"], + float(data["IR_temperature"]) + ) + + self.SQLOperate(sql) logging.debug('Insert sensors_data success') except: # Rollback in case there is any error - db.rollback() + self.db_hander.rollback() logging.error("Insert error,database rollback.") logging.debug(sql) PrintException() - except: - db.close() - -def Insert_logs(event, host="163.17.135.169", user="pi", password="raspberry", database="libRaspberry", port=3306): - try: - db = MySQLdb.connect(host, user, password, database, port) - cursor = db.cursor() + def Insert_logs(self, event): try: sql = "insert into logs(event) values('{}');".format(event) - cursor.execute(sql) - db.commit() + self.SQLOperate(sql) logging.debug("Insert log success") - cursor.close() - db.close() except: - db.rollback() + self.db_hander.rollback() logging.error("Insert log error") PrintException() - cursor.close() - db.close() - except: - logging.error("connect database error") - PrintException() - - -if __name__ == "__main__": - Send_Sensors() -======= -# -*- coding: utf-8 -*- -# vim:fenc=utf-8 -# Last modified: 2017-05-16 20:55:48 - -import sys -import time -import json -import os -from . import send -import math -import subprocess -import re -import datetime -import logging - -from abc import ABCMeta, abstractmethod -from package.debug import PrintException - -# Third party -import MySQLdb -from package.dht11 import libDHT11 -from package import TMP006 -from adxl345 import ADXL345 -# import from third party lib -sys.path.append("/usr/lib/python2.7/site-packages/") -from printrun.printcore import printcore -from printrun import gcoder - - -class CommandSwitchTableProto(object): - - metaclass__ = ABCMeta - - def __init__(self, *args, **kwargs): - self.task = { - "connect": self.connect, - "disconnect": self.disconnect, - "reset": self.reset, - "pause": self.pause, - "resume": self.resume, - "cancel": self.cancel, - "cooldown": self.cooldown, - "home": self.home, - "startprint": self.startprint, - "stepperoff": self.stepperoff, - "send_now": self.send_now, - "printer_status": self.printer_status, - "headtemp": self.headtemp, - "Default": self.Default - } - - @abstractmethod - def getTask(self, command): - pass - - def getcommands(self): - return self.task.keys - - @abstractmethod - def connect(self): - pass - - @abstractmethod - def disconnect(self): - pass - - @abstractmethod - def reset(self): - pass - - @abstractmethod - def resume(self): - pass - - @abstractmethod - def cancel(self): - pass - - @abstractmethod - def cooldown(self): - pass - - @abstractmethod - def home(self): - pass - - @abstractmethod - def startprint(self): - pass - - @abstractmethod - def stepperoff(self): - pass - - @abstractmethod - def send_now(self): - pass - - @abstractmethod - def printer_status(self): - pass - - @abstractmethod - def headtemp(self): - pass - - def Default(self): - print("No command") - - -class PrintCore(object): - Port = '/dev/ttyUSB0' - Baud = 250000 - - def __init__(self, Port=None, Baud=None): - self.printcoreHandler = printcore() - self.logl = 0 - self.temp = 0 - - def connect(self, Port='/dev/ttyUSB0', Baud=250000): - try: - self.printcoreHandler.connect(port=Port, baud=Baud) - # must wait for printcore connect success - time.sleep(3) - setattr(self.printcoreHandler, 'logl', 0) - except: - PrintException() - - def disconnect(self): - try: - self.printcoreHandler.disconnect() - return True - except: - PrintException() - return False - - def is_printing(self): - return self.printcoreHandler.printing - - def reset(self): - self.printcoreHandler.reset() - print('py:reset print') - return True - - def pause(self): - self.printcoreHandler.pause() - print('py:pause print') - return True - - def resume(self): - self.printcoreHandler.resume() - print('py:resume print') - return True - - def cancel(self): - self.printcoreHandler.cancelprint() - self.printcoreHandler.send_now("M104 S0") # cool dowm - self.printcoreHandler.send_now("G28") # home - self.printcoreHandler.send_now("M84") # stepperoff - print("py:cancel print") - return True - - def cooldown(self): - self.printcoreHandler.send_now("M104 S0") - print('py:cooldown') - return True - - def home(self): - self.printcoreHandler.send_now("G28") - print('py:home') - return True - - def send_now(self, command): - try: - self.printcoreHandler.send_now(command) - print("send command success") - return True - except: - print("py:send command failed") - return False - - def startprint(self, file): - try: - print('start print...') - gcode = [i.strip() for i in open(file)] - gcode = gcoder.LightGCode(gcode) - self.printcoreHandler.startprint(gcode) - print("py:print") - return True - except: - self.cancel() - PrintException() - return False - - def stepperoff(self): - self.printcoreHandler.send_now("M84") - print('py:stepper off') - return True - - def isPaused(self): - return self.printcoreHandler.paused - - def printer_status(self): - """get printer status into json file - - :p: printer object - :return: return json string - - """ - data = {} - data["clear"] = self.printcoreHandler.clear - data["isprinting"] = self.printcoreHandler.printing - data["online"] = self.printcoreHandler.online - data["baud"] = self.printcoreHandler.baud - data["port"] = self.printcoreHandler.port - try: - data["IR_temperature"] = self.headtemp() - data["position"] = self.getPosition() - except: - pass - data["ispause"] = self.isPaused() - return data - - def gettemp(self): - self.printcoreHandler.send_now("M105") - try: - self.printcoreHandler.logl - self.temp - except: - setattr(self, 'logl', 0) - setattr(self, 'temp', 0) - - if(self.printcoreHandler.online is False): - return None - for n in range(self.printcoreHandler.logl, len(self.printcoreHandler.log)): - line = self.printcoreHandler.log[n] - if 'T:' in line: - te = line.split('T:')[1] - htemp = float(te.split("/")[0].strip()) - setattr(self, 'temp', htemp) - self.printcoreHandler.logl = len(self.printcoreHandler.log) - self.printcoreHandler.send_now("M105") - return htemp - return None - - def headtemp(self): - try: - return self.gettemp() - except: - logging.error("py:get headtemp error occure") - PrintException() - return 0 - - def getPosition(self): - try: - self.printcoreHandler.send_now("M114") - time.sleep(1) - for n in range(self.printcoreHandler.logl, len(self.printcoreHandler.log)): - line = self.printcoreHandler.log[n] - if("X:"in line): - return line.strip() - except: - logging.debug("Printcore:get position error.") - return '' - - -def create_json_file(path, data): - """write a json file to path - :path: data to be store - :data: data to be send - :return: write success return file path else None - """ - try: - beSended = json.dumps(data) - with open(os.path.join(path), 'w') as file: - file.write(beSended) - except Exception as e: - print((e.args)) - - -class sensors(object): - - def __init__(self): - self.humidity = 0 - self.temperature = 0 - - def get_current_time(self): - return str(datetime.datetime.now()) - - def DHT11_temp(self): - try: - # have to use libDHT11.Init_WiringPi() first - checksum = 0 - # while checksum is not 0: - humidity, humidityfloat, temperature, temperaturefloat, checksum = libDHT11.read_DHT11() - - while True: - if checksum is not 0: - break - else: - humidity, humidityfloat, temperature, temperaturefloat, checksum = libDHT11.read_DHT11() - - data = {"humidity": humidity, "humidityfloat": humidityfloat, - "temperature": temperature, "temperaturefloat": temperaturefloat} - - if(humidity + temperature != checksum): - data["humidity"] = self.humidity - data["temperature"] = self.temperature - - self.humidity = data["humidity"] - self.temperature = data["temperature"] - - return data - except: - PrintException() - return {} - - def get_G_sensor(self): - - try: - adxl345 = ADXL345() - axes = adxl345.getAxes(True) - - g_x = (axes['x']) - g_y = (axes['y']) - g_z = (axes['z']) - - return g_x, g_y, g_z - except: - PrintException() - return {} - - def IR_temp(self): - try: - # IR Temperature: - sensor = TMP006.TMP006() - sensor.begin() - obj_temp = sensor.readObjTempC() - die_temp = sensor.readDieTempC() - return obj_temp - except: - PrintException() - return {} - - def get_Sensors_data(self): - try: - data = self.DHT11_temp() - (data["g_x"], data["g_y"], data["g_z"]) = self.get_G_sensor() - data["time"] = self.get_current_time() - - return data - except: - PrintException() - return {} - - -class SqlManager(object): - - def __init__(self, host, user, password, database, port): - self.host = host - self.user = user - self.password = password - self.database = database - self.port = port - self.db_hander = MySQLdb.connect(host, user, password, database, port) - self.cursor = self.db_hander.cursor() - - def __del__(self): - self.cursor.close() - self.db_hander.close() - logging.debug("close SqlManager success") - - def SQLOperate(self, sqlcommand): - try: - # Execute the SQL command - self.cursor.execute(sqlcommand) - self.db_hander.commit() - except: - PrintException() - - def Send_Sensors(self, data={}): - try: - # Prepare SQL query to INSERT a record into the database. - sql = "Insert into env_data(humidity,temperature,x_axis,y_axis,z_axis,IR_temperature) values({},{},{},{},{},{})".format( - data["humidity"], - data["temp"], - data["g_x"], - data["g_y"], - data["g_z"], - float(data["IR_temperature"]) - ) - - self.SQLOperate(sql) - logging.debug('Insert sensors_data success') - except: - # Rollback in case there is any error - self.db_hander.rollback() - logging.error("Insert error,database rollback.") - logging.debug(sql) - PrintException() - - def Insert_logs(self, event): - try: - sql = "insert into logs(event) values('{}');".format(event) - self.SQLOperate(sql) - logging.debug("Insert log success") - except: - self.db_hander.rollback() - logging.error("Insert log error") - PrintException() ->>>>>>> dev diff --git a/src/python/server.py b/src/python/server.py index 057308c..d459798 100644 --- a/src/python/server.py +++ b/src/python/server.py @@ -1,309 +1,97 @@ -<<<<<<< HEAD # -*- coding: utf-8 -*- # vim:fenc=utf-8 -# Last modified: 2016-11-30 20:59:13 +# Last modified: 2018-05-31 10:38:04 -import socket -import da +import os import sys import logging -import os -import subprocess -import shlex -import multiprocessing +import threading from package.thread_pool import ThreadPool -from threading import Thread -from time import sleep -from package.send import upload_server -from package.s_printer_status import S_printer_status from package.debug import PrintException -from package.sock_proto import TCP_Server -from package.da import PrintCore -from package.da import CommandSwitchTableProto -from package import da -from package import DHT11 -from package.printtime import check_print_time -import threading - - -# path to put gcode -filepath = "/home/pi/temp/" - - -class Switcher(CommandSwitchTableProto): - - class SendData(object): - - def __init__(self, printercore): - self.printcore = printercore - self.fileName = "" - self.lock = True - - def stopRunning(self): - self.lock = False - - def stopped(self): - return self.lock +from package.Switcher import Switcher +from package.redis_object import redis_handler +from package.environment_config import UseConfigs +from package.dht11 import libDHT11 - def set_file_name(self, filename): - self.fileName = filename - def __st_Sensors(self): - sensors_data = da.get_Sensors_data() - if sensors_data is not None: - sensors_data["IR_temperature"] = self.printcore.headtemp() - da.Send_Sensors(data=sensors_data) +class Server(object): - def __createJsonData(self): - # get printer status data - data = self.printcore.printer_status() - - # get filename if startprint is start - data["File_Name"] = self.fileName - if self.fileName is not "": - # TODO:printtime - # data["PrintTime"] = self.__printtimeHandler.end_time() - pass - logging.debug(data) - return data - - def Thread_InsertSensors(self): - while self.stopped(): - # inset sensors data into database - self.__st_Sensors() - sleep(1) - - def SendJsonToRemote(self): - S_printer_status(self.__createJsonData()) - - def Thread_SendJsonData(self): - while self.stopped(): - # start json file - self.SendJsonToRemote() - logging.debug("run st_thread success!") - - def __init__(self): - super(Switcher, self).__init__() - # handlers - self.printcore = None - self.__rtmpprocess = None - self.sendData = None + def __init__(self, Directory="/home/pi/Rpi3dPrinter"): + self.directory = os.path.join(Directory) self.pool = ThreadPool(6) + self.stopped = threading.Event() + self.check_directory() + self.config_file_path = os.path.join(self.directory, "config_file.json") + libDHT11.Init_WiringPi() + self.config = UseConfigs(self.config_file_path) + self.check_config() + self.redis_handler = redis_handler(Host=self.config.config["redis_ip"], + Port=self.config.config["redis_port"], + master=self.config.config["redis_master"], + slaver=self.config.config["redis_slaver"], + password=self.config.config["redis_password"]) + + self.switcher = Switcher(self.redis_handler, self.directory, self.pool) + self.isStopped = False + + def Thread_main(self): + logging.basicConfig(level=logging.DEBUG) + try: + print("server listening...") + # wait for message + while True: + # for message in self.redis_handler.pubsub.listen(): + message = self.redis_handler.pubsub.get_message() + if message: + try: + src = message.get('data').decode('utf-8') + print(("Client send:" + src)) + check = self.switcher.getTask(src) + # self.redis_handler.send(check) + except: + PrintException() + else: + self.switcher.Thread_add_Send_Sensors() + except KeyboardInterrupt: + print("KeyboardInterrupt! Stop server") + self.stopped.set() + sys.exit(0) + except: + PrintException() - # TODO:check print time - # self.__printtimeHandler = check_print_time() - - def getTask(self, command): - listcommand = command.split(" ", 1) - print("command list:", listcommand) - if listcommand[0].strip() not in self.task: - self.Default() - return "No Command!" - - da.Insert_logs(listcommand[0]) - if len(listcommand) > 1: - self.task.get(listcommand[0].strip())(listcommand[1].strip()) - else: - self.task.get(listcommand[0].strip())() - return "Command Send Success" - - def __check_gcode(self, filename): - if filename.split(".")[-1] == "gcode": - return True - else: - return False - - def connect(self): - self.printcore = PrintCore(Port='/dev/ttyUSB0', Baud=250000) - self.sendData = self.SendData(self.printcore) - if self.printcore is not None: - self.pool.add_task(self.sendData.Thread_InsertSensors) - self.pool.add_task(self.sendData.Thread_SendJsonData) - else: - logging.error("Connect printer error!") + def run_main(self): + self.pool.add_task(self.Thread_main()) - def disconnect(self): - self.printcore.disconnect() - self.sendData.stopRunning() + def __del__(self): + self.close_main() self.pool.wait_completion() - self.sendData.SendJsonToRemote() - - def reset(self): - self.printcore.reset() - - def pause(self): - self.printcore.pause() - - def resume(self): - self.printcore.resume() - - def cancel(self): - self.printcore.cancel() - - def home(self): - self.printcore.home() - - def send_now(self, command): - self.printcore.send_now(command.strip("\n")) - - def startprint(self, ClientFilePath): - - filename = ClientFilePath.split("/")[-1] - print("receive file name", filename) - self.sendData.set_file_name(filename) - - newfilepath = os.path.join(filepath, filename) - self.__printtimeHandler.print_time(newfilepath) - if self.__check_gcode(filename): - upload_server(newfilepath) - self.printcore.startprint(newfilepath) - else: - print("not gcode file") + def check_directory(self): + # check directory is exists + if not os.path.exists(self.directory): + os.makedirs(self.directory) - def Default(self): - print("no command") + def check_config(self): + if not self.config.check_config(): + self.config.make_config() + self.config.load_config() - -def main(): - DHT11.Init_WiringPi() - sock = TCP_Server() - switcher = Switcher() - - # prepare for file directory - if not os.path.exists(filepath): - os.makedirs(filepath) - - while True: - try: - logging.debug("server accept") - sock.WaitForConnecting() - src = sock.Client.recv(1024) - if not src: - logging.debug("command failed") - continue - else: - print("Client send:" + src) - check = switcher.getTask(src) - sock.Client.send(check) - except KeyboardInterrupt: - print("KeyboardInterrupt! Stop server") - sys.exit(0) - break - except socket.timeout: - print("Time out") - PrintException() - except Exception, ex: - PrintException() - finally: - sock.Client.close() + def close_main(self): + self.isStopped = False if __name__ == "__main__": + logging.basicConfig(filename='printer3d.log', + level=logging.DEBUG + ) try: - logging.basicConfig(level=logging.DEBUG) - main() + # path to put gcode + directory = "/home/pi/Rpi3dPrinter" + server = Server(directory) + server.run_main() except KeyboardInterrupt: - print("KeyboardInterrupt! Stop server") + PrintException() sys.exit(0) except: PrintException() -======= -# -*- coding: utf-8 -*- -# vim:fenc=utf-8 -# Last modified: 2017-07-04 17:18:58 - -import os -import sys -import logging -import threading -from package.thread_pool import ThreadPool -from package.debug import PrintException -from package.Switcher import Switcher -from package.redis_object import redis_handler -from package.environment_config import UseConfigs -from package.dht11 import libDHT11 - - -class Server(object): - - def __init__(self, Directory="/home/pi/Rpi3dPrinter"): - self.directory = os.path.join(Directory) - self.pool = ThreadPool(6) - self.stopped = threading.Event() - self.check_directory() - self.config_file_path = os.path.join(self.directory, "config_file.json") - libDHT11.Init_WiringPi() - self.config = UseConfigs(self.config_file_path) - self.check_config() - self.redis_handler = redis_handler(Host=self.config.config["redis_ip"], - Port=self.config.config["redis_port"], - master=self.config.config["redis_master"], - slaver=self.config.config["redis_slaver"], - password=self.config.config["redis_password"]) - - self.switcher = Switcher(self.redis_handler, self.directory, self.pool) - self.isStopped = False - - def Thread_main(self): - logging.basicConfig(level=logging.DEBUG) - try: - print("server listening...") - # wait for message - while True: - # for message in self.redis_handler.pubsub.listen(): - message = self.redis_handler.pubsub.get_message() - if message: - try: - src = message.get('data').decode('utf-8') - print(("Client send:" + src)) - check = self.switcher.getTask(src) - # self.redis_handler.send(check) - except: - PrintException() - else: - self.switcher.Thread_add_Send_Sensors() - except KeyboardInterrupt: - print("KeyboardInterrupt! Stop server") - self.stopped.set() - sys.exit(0) - except: - PrintException() - - def run_main(self): - self.pool.add_task(self.Thread_main()) - - def __del__(self): - self.close_main() - self.pool.wait_completion() - - def check_directory(self): - # check directory is exists - if not os.path.exists(self.directory): - os.makedirs(self.directory) - - def check_config(self): - if not self.config.check_config(): - self.config.make_config() - self.config.load_config() - - def close_main(self): - self.isStopped = False - - -if __name__ == "__main__": - logging.basicConfig(filename='printer3d.log', - level=logging.DEBUG - ) - try: - # path to put gcode - directory = "/home/pi/Rpi3dPrinter" - server = Server(directory) - server.run_main() - except KeyboardInterrupt: - PrintException() - sys.exit(0) - except: - PrintException() - sys.exit(0) ->>>>>>> dev + sys.exit(0)