增加高压空闲调节

This commit is contained in:
2026-06-10 11:23:24 +08:00
parent ee45729b5b
commit d44140d999
123 changed files with 22413 additions and 0 deletions
+1
View File
@@ -174,3 +174,4 @@ cython_debug/
# PyPI configuration file # PyPI configuration file
.pypirc .pypirc
.vscode/
+7
View File
@@ -0,0 +1,7 @@
{
"id": 2,
"code": "2#HVS",
"mb_addr": 2,
"xray_ctrl_pin_enable" : false,
"watchdog_enable": false
}
+1
View File
@@ -0,0 +1 @@
{"kV": 55, "filament": {"preheat": 500, "limit": 1500}, "mA": 0.60, "selfTest": true,"xrayAdjustTime": 800}
+19
View File
@@ -0,0 +1,19 @@
{
"broker": {
"ip": "123.57.81.127",
"port": 1888,
"clientid": "hv_controller_",
"user": "mqtt",
"passwd": "123456"
},
"topic": {
"sub": [
"/dev/param/hsv/1",
"/dev/control/hsv/1"
],
"pub": {
"status": "/dev/status/hsv/1",
"response": "/dev/response/hsv/1"
}
}
}
+1
View File
@@ -0,0 +1 @@
{"hv": {"loadPwm": 224, "limitPwm": 350, "idlePwm": 188}, "filament": {"preheatPwm": 100, "normalPwm": 285, "limitPwm": 320}}
+996
View File
@@ -0,0 +1,996 @@
import machine
from machine import PWM
from machine import ADC
from machine import Filament
from machine import WDT
from machine import Pin
from machine import Fram
import sys
import time
import _thread
import json
import gc
import math
import os
from webserver import send_ws, send_ws_list, py_server
# ----------------------------------------------------------------------------
from script.umodbus.serial import ModbusRTU
wdt = None
mb_server = None
selfTestTime = 0
pwmDuty = 0
pwmDutyRayOn = 0
filament = Filament(3)
filament.init()
filament.set_relay(False)
#PWM
hvPwm = PWM('pwm1', 2, 46000, 0, 50, False)
hvPwmn = PWM('pwm1', 3, 46000, 1023, 50, False)
#ADC
hvAdc = ADC('adc1', 16) # HV Voltage
hiAdc = ADC('adc3', 0) # HV Current
tempAdc = ADC('adc2', 15) # HV NTC
hvAdc.average(50)
hiAdc.average(50)
tempAdc.average(50)
hvAdcValue = 0
hvKvValue = 0
hvSwitch = False
raySwitch = False
raySwitchPin = Pin(('GPIOC', 6))
raySwitchPin.init(Pin.IN)
rayStartTime = 0
web_socket_list = []
wslock = None
filaInfo = {
'relay_stat' : False,
'vout' : 0,
'iout' : 0,
'vin' : 0,
'iin' : 0
}
sysErrorList = []
sysInfoList = []
hiAdcValue = 0
hiMaValue = 0
himAOverLimitCount = 0
hvTempValue = 0
filamentCurrent = 0
filamentVoltage = 0
filamentDuty = 0
filamentLoadDuty = 0
averageBuffer = {
"hvIdleKv" : [],
"hvLoadKv" : [],
"fiPreheatCurrent": [],
"hvLoadMa": []
}
config = {
"dev" : {
"code" : "1#HVS",
"id" : "12345",
},
"mqtt" : {},
"hv" : {
"kV": 70,
"filament": {
"preheat": 300,
"limit": 1200
},
"mA": 0.7,
"xrayAdjustTime": 600,
"selfTest" : False
},
"var" : {
"hv" : {
"idlePwm" : 200,
"loadPwm" : 320,
"limitPwm" : 450
},
"filament" : {
"preheatPwm": 50,
"limitPwm": 300,
"normalPwm": 260
}
}
}
def averageBufferPut(key, value):
global averageBuffer
if key in averageBuffer:
averageBuffer[key].append(value)
if len(averageBuffer[key]) > 20:
averageBuffer[key].pop(0)
def averageBufferGetAverage(key, n):
global averageBuffer
if key in averageBuffer:
values = averageBuffer[key]
if len(values) < n:
return None
average = sum(values[:n]) / n
return average
return None
def mb_control_cb(reg_type, address, val):
global hvSwitch, raySwitch, sysInfoList
print('control',reg_type,address,val)
for value in val:
if address == 0:
hvSwitch = value == True
# mb_server.set_coil(7 - 0, hvSwitch)
print("hvSwitch:",hvSwitch)
info = {
"event" : "hvSwitch",
"from" : "modbus",
"value" : hvSwitch,
"time" : time.ticks_ms()
}
sysInfoList.append(info)
elif address == 1:
if value == True:
print('alarm clear')
# mb_server.set_coil(1, False)
elif address == 2:
if config['dev']['xray_ctrl_pin_enable']:
return
raySwitch = value == True
# mb_server.set_coil(7 - 2, raySwitch)
print("raySwitch:",raySwitch)
info = {
"event" : "raySwitch",
"from" : "modbus",
"value" : raySwitch,
"time" : time.ticks_ms()
}
sysInfoList.append(info)
address += 1
def mb_param_cb(reg_type, address, val):
print('param',reg_type,address,val)
for value in val:
if address == 0:
config['hv'].update({'kV' : value / 100.0})
elif address == 1:
config['hv'].update({'mA' : value / 1000.0})
elif address == 2:
config['hv']['filament'].update({'limit' : value})
elif address == 3:
config['hv']['filament'].update({'preheat' : value})
address += 1
save_config('hv')
mb_register_definitions = {
"COILS": {
"control": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0],
"on_set_cb": mb_control_cb
}
},
"HREGS": {
"params": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0],
"on_set_cb": mb_param_cb
}
},
"ISTS": {
"status": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0]
}
},
"IREGS": {
"input": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0]
}
}
}
def load_config():
global config
config_path = "/config/hv.json"
try:
with open(config_path, 'r') as f:
config['hv'] = json.load(f)
except OSError as e:
print("文件操作错误:", e)
except ValueError as e:
print("JSON 解析错误:", e)
config_path = "/config/mqtt.json"
try:
with open(config_path, 'r') as f:
config['mqtt'] = json.load(f)
except OSError as e:
print("文件操作错误:", e)
except ValueError as e:
print("JSON 解析错误:", e)
config_path = "/config/dev.json"
try:
with open(config_path, 'r') as f:
config['dev'] = json.load(f)
except OSError as e:
print("文件操作错误:", e)
except ValueError as e:
print("JSON 解析错误:", e)
config_path = "/config/var.json"
var = None
try:
varBuf = Fram.read(0, 512)
var = json.loads(varBuf)
except ValueError as e:
print("JSON 解析错误:", e)
var = None
if var:
config['var'] = var
with open(config_path, 'w') as f:
json.dump(var, f)
print('write var.json', var)
else:
try:
with open(config_path, 'r') as f:
config['var'] = json.load(f)
Fram.write(0, json.dumps(config['var']).encode() + b'\x00')
except OSError as e:
print("文件操作错误:", e)
except ValueError as e:
print("JSON 解析错误:", e)
def save_config(config_type):
if config_type == 'var':
Fram.write(0, json.dumps(config['var']).encode() + b'\x00')
return
try:
data = config[config_type]
config_path = "/config/" + config_type + '.json'
with open(config_path, 'w') as f:
f.write(json.dumps(data))
except OSError as e:
print("文件操作错误:", e)
def mb_init():
global mb_server
print("mb_init...")
mb_server = ModbusRTU(addr = config['dev']['mb_addr'],baudrate=115200,uart_id=4,ctrl_pin=-2)
mb_server.setup_registers(registers=mb_register_definitions)
mb_server.set_hreg(0, [
int(config['hv']['kV'] * 100),
int(config['hv']['mA'] * 1000),
int(config['hv']['filament']['limit']),
int(config['hv']['filament']['preheat']),
])
mb_server.set_coil(0, hvSwitch)
mb_server.set_coil(2, raySwitch)
# if not mb_server.get_bound_status():
# mb_server.bind(local_ip='0.0.0.0', local_port=502)
# print("start mb tcp server")
def adc2temp(adc_val):
Rt = adc_val * 10000.0 / (65535 - adc_val)
Rp = 10000.0
T2 = 273.15 + 25.0
Bx = 3950.0
Ka = 273.15
temp = 0.0
temp = Rt / Rp
temp = math.log(temp)
temp /= Bx
temp += (1 / T2)
temp = 1 / temp
temp -= Ka
return temp
def hvAdc2kV(hv):
return hv / 65535.0 * 3.0 * 3 * 10
def hiAdc2mA(hi):
return hi / 65535.0 * 3.0 * 3 / 4.4
#read hv voltage and current, num times, and return the average value
def hvAdcRead(num, delay):
global filaInfo
sumHv = 0
sumHi = 0
for i in range(num):
sumHv += hvAdc.read()
sumHi += hiAdc.read()
time.sleep_ms(delay)
sumHv /= num
sumHi /= num
filaInfo = filament.read()
fv = filaInfo['vout']
fi = filaInfo['iout']
return sumHv, sumHi, fv, fi
def hvAdcRead():
global filaInfo
sumHv = hvAdc.average()
sumHi = hiAdc.average()
filaInfo = filament.read()
fv = filaInfo['vout']
fi = filaInfo['iout']
return sumHv, sumHi, fv, fi
def hvAdcPoll(count, delay):
global hvAdcValue, hvKvValue, hiAdcValue, hiMaValue
global filamentDuty, filamentCurrent, filamentVoltage
hv, hi, fv, fi = hvAdcRead()
hvAdcValue = hv
hiAdcValue = hi
hvKvValue = hvAdc2kV(hv)
hiMaValue = hiAdc2mA(hi)
filamentCurrent = fi
filamentVoltage = fv
# control the filament current
def filamentPreheat(fiPreheat):
global filamentCurrent, filamentVoltage, filamentDuty
tmpDuty = filamentDuty
fi = filamentCurrent
if fi > fiPreheat + 100:
tmpDuty -= 2
elif fi > fiPreheat + 50:
tmpDuty -= 1
elif fi < fiPreheat - 100:
tmpDuty += 2
elif fi < fiPreheat - 50:
tmpDuty += 1
if tmpDuty < 0:
tmpDuty = 0
elif tmpDuty > 750:
tmpDuty = 750
filament.set_duty(tmpDuty)
filamentDuty = tmpDuty
# print('preheat', fiPreheat, tmpDuty)
# control the filament current
def filamentPreheatFast(fiPreheat):
global filamentCurrent, filamentVoltage, filamentDuty
if fiPreheat < 0.01:
tmpDuty = 0
filament.set_duty(tmpDuty)
filamentDuty = tmpDuty
return
tmpDuty = config['var']['filament']['preheatPwm']
fi = filamentCurrent
if tmpDuty > config['var']['filament']['limitPwm']:
tmpDuty = config['var']['filament']['limitPwm']
if filamentDuty != tmpDuty:
filament.set_duty(tmpDuty)
filamentDuty = tmpDuty
# print('preheat', fiPreheat, tmpDuty)
else:
averageBufferPut('fiPreheatCurrent', filamentCurrent)
# control the filament current
def filamentControlNormal(hiAim, fiLimit):
global filamentCurrent, filamentVoltage, filamentDuty
tmpDuty = filamentDuty
hi = hiMaValue
fi = filamentCurrent
delta = (hi - hiAim) * 1000
if delta < 0:
val = -delta
else:
val = delta
daDelta = 0
if val > 200:
daDelta = 2
elif val > 40:
daDelta = 1
elif val > 10:
daDelta = 0
elif val > 5:
daDelta = 0
else:
daDelta = 0
if fi > fiLimit:
tmpDuty -= 10
elif delta > 0:
tmpDuty -= daDelta
elif delta < 0:
tmpDuty += daDelta
if tmpDuty < 0:
tmpDuty = 0
elif tmpDuty > config['var']['filament']['limitPwm']:
tmpDuty = config['var']['filament']['limitPwm']
filament.set_duty(tmpDuty)
# filament.set_duty(0)
filamentDuty = tmpDuty
# control the filament current
def filamentControlFast(hiAim):
global filamentCurrent, filamentVoltage, filamentDuty, filamentLoadDuty
tmpDuty = filamentDuty
if raySwitch:
deltaTime = 0
if rayStartTime > 1:
now = time.ticks_ms()
deltaTime = time.ticks_diff(now, rayStartTime)
if deltaTime > config['hv']['xrayAdjustTime']:
if deltaTime > config['hv']['xrayAdjustTime'] + 200:
if hvKvValue > config['hv']['kV'] - 2 and filamentDuty >= config['var']['filament']['normalPwm']:
filamentLoadDuty = filamentDuty
averageBufferPut('hvLoadMa', hiMaValue)
elif hiMaValue > config['hv']['mA'] + 0.05 and filamentDuty >= config['var']['filament']['normalPwm']:
filamentLoadDuty = filamentDuty
averageBufferPut('hvLoadMa', hiMaValue)
return
if hiMaValue > hiAim:
tmpDuty = tmpDuty - 2
else:
aimDuty = config['var']['filament']['normalPwm']
if tmpDuty < aimDuty - 0.2:
tmpDuty = tmpDuty + 10
elif tmpDuty < aimDuty:
tmpDuty = tmpDuty + 5
if tmpDuty > aimDuty:
tmpDuty = aimDuty
if hvKvValue < config['hv']['kV'] - 2:
return
if tmpDuty > config['var']['filament']['limitPwm']:
tmpDuty = config['var']['filament']['limitPwm']
filamentDuty = int(tmpDuty)
filament.set_duty(filamentDuty)
#print('filamentDuty adjust', filamentDuty)
# filament.set_duty(0)
def hvControlFast(hvAim):
global pwmDuty, rayStartTime, pwmDutyRayOn
if not hvSwitch:
pwmDuty = 0
hvPwm.duty(pwmDuty)
hvPwmn.duty(1023 - pwmDuty)
return
if not raySwitch:
tmpDuty = config['var']['hv']['idlePwm']
if pwmDuty > tmpDuty:
pwmDuty = tmpDuty
hvPwm.duty(pwmDuty)
hvPwmn.duty(1023 - pwmDuty)
print("hv adjust to idle", pwmDuty)
elif pwmDuty < tmpDuty:
pwmDuty = pwmDuty + 3
if pwmDuty > tmpDuty:
pwmDuty = tmpDuty
hvPwm.duty(pwmDuty)
hvPwmn.duty(1023 - pwmDuty)
print("hv adjust to idle", pwmDuty)
else:
averageBufferPut('hvIdleKv', hvKvValue)
return
deltaTime = 0
if rayStartTime > 1:
now = time.ticks_ms()
deltaTime = time.ticks_diff(now, rayStartTime)
if deltaTime > config['hv']['xrayAdjustTime'] + 200:
averageBufferPut('hvLoadKv', hvKvValue)
pwmDutyRayOn = pwmDuty
if deltaTime > config['hv']['xrayAdjustTime']:
return
if pwmDuty == config['var']['hv']['loadPwm']:
return
tmpDuty = pwmDuty
if hiMaValue > config['hv']['mA']:
return
if hvKvValue < config['hv']['kV'] - 3:
tmpDuty = tmpDuty + 2
elif hvKvValue < config['hv']['kV']:
tmpDuty = tmpDuty + 1
if tmpDuty > config['var']['hv']['loadPwm']:
tmpDuty = config['var']['hv']['loadPwm']
if pwmDuty > config['var']['hv']['limitPwm']:
pwmDuty = config['var']['hv']['limitPwm']
pwmDuty = tmpDuty
hvPwm.duty(pwmDuty)
hvPwmn.duty(1023 - pwmDuty)
print("hv adjust", deltaTime, pwmDuty)
def hvControl(hvAim):
global pwmDuty
if not hvSwitch:
pwmDuty = 0
hvPwm.duty(pwmDuty)
hvPwmn.duty(1023 - pwmDuty)
return
hv = hvKvValue
pwmVal = pwmDuty
delta = (hv - hvAim) * 1000
if delta < 0:
val = -delta
else:
val = delta
pwmDelta = 0
if val > 20000:
pwmDelta = 3
elif val > 10000:
pwmDelta = 2
elif val > 1000:
pwmDelta = 1
else:
pwmDelta = 0
if delta > 0:
pwmVal -= pwmDelta
elif delta < 0:
pwmVal += pwmDelta
if pwmVal < 0:
pwmVal = 0
elif pwmVal > 300:
pwmVal = 300
#pwmVal = 30
hvPwm.duty(pwmVal)
hvPwmn.duty(1023 - pwmVal)
if pwmDuty != pwmVal:
pwmDuty = pwmVal
print("pwm:%d,%d"%(pwmDelta, pwmDuty))
def mb_reg_update():
mb_server.set_coil(0, hvSwitch)
mb_server.set_coil(2, raySwitch)
mb_server.set_ireg(0, [
int(hvKvValue * 100),
int(hiMaValue * 1000),
int(filamentCurrent),
int(hvTempValue)
])
def ws_status_update():
status = {
'param' : {
'kV' : config['hv']['kV'],
'mA' : config['hv']['mA']
},
'value' : {
'hv' : 'on' if hvSwitch else 'off',
'xray' : 'on' if raySwitch else 'off',
'kV' : hvKvValue,
'mA' : hiMaValue,
'fV' : filamentVoltage / 1000,
'fI' : filamentCurrent / 1000,
'Vin' : filaInfo['vin'] / 1000,
'Iin' : filaInfo['iin'] / 1000
}
}
send_ws_list('/dev/status/hsv', status)
def ws_cmd_handler(ws, payload):
global hvSwitch, raySwitch, sysInfoList, sysErrorList
obj = json.loads(payload)
msg = obj['message']
dev_id = msg['device_id']
dev_code = msg['device_code']
cmd = msg['command']
if cmd == 'set_params':
value = msg['value']
if 'filament' in value:
config['hv']['filament'].update(value['filament'])
del value['filament']
config['hv'].update(value)
mb_server.set_hreg(0, [
int(config['hv']['kV']),
int(config['hv']['mA'] * 1000),
int(config['hv']['filament']['limit']),
int(config['hv']['filament']['preheat']),
])
print(config['hv'])
save_config('hv')
elif cmd == 'get_params':
msg = config['dev']
msg['command'] = cmd
msg['value'] = config['hv']
send_ws(ws, '/dev/response/hsv', msg)
elif cmd == 'hv_control':
hvSwitch = msg['value'] == 'on'
mb_server.set_coil(0, hvSwitch)
print("hvSwitch:",hvSwitch)
send_ws(ws, '/dev/response/hsv', msg)
info = {
"event" : "hvSwitch",
"from" : "web",
"value" : hvSwitch,
"time" : time.ticks_ms()
}
sysInfoList.append(info)
elif cmd == 'ray_control':
if config['dev']['xray_ctrl_pin_enable']:
return
raySwitch = msg['value'] == 'on'
mb_server.set_coil(2, raySwitch)
print("raySwitch:",raySwitch)
send_ws(ws, '/dev/response/hsv', msg)
info = {
"event" : "raySwitch",
"from" : "web",
"value" : raySwitch,
"time" : time.ticks_ms()
}
sysInfoList.append(info)
elif cmd == 'get_var':
msg['command'] = cmd
msg['value'] = {
'time' : time.ticks_ms(),
'var' : config['var'],
'error' : sysErrorList,
'info' : sysInfoList
}
send_ws(ws, '/dev/response/hsv', msg)
elif cmd == 'set_var':
if 'var' in msg['value']:
value = msg['value']['var']
else:
value = msg['value']
config['var'].update(value)
save_config('var')
def hvVarCollect():
if not hvSwitch:
return
if raySwitch:
aim = config['hv']['mA']
if hiMaValue < aim * 1.05 and hiMaValue > aim * 0.95:
config['var']['hv']['loadPwm'] = pwmDuty
else:
aim = config['hv']['kV']
if hvKvValue < aim + 1 and hvKvValue > aim - 1:
config['var']['hv']['idlePwm'] = pwmDuty
def filamentVarCollect():
if not hvSwitch:
return
if raySwitch:
aim = config['hv']['mA']
if hiMaValue < aim * 1.05 and hiMaValue > aim * 0.95:
config['var']['filament']['normalPwm'] = filamentDuty
else:
aim = config['hv']['filament']['preheat']
if filamentCurrent < aim + 50 and filamentCurrent > aim - 50:
config['var']['filament']['preheatPwm'] = filamentDuty
def varCheckAndSave():
save_config('var')
def varUpdate():
hvIdleKv = averageBufferGetAverage('hvIdleKv', 10)
hvLoadKv = averageBufferGetAverage('hvLoadKv', 10)
fiPreheatCurrent = averageBufferGetAverage('fiPreheatCurrent', 10)
hvLoadMa = averageBufferGetAverage('hvLoadMa', 10)
print('hvIdleKv', hvIdleKv)
print('hvLoadKv', hvLoadKv)
print('fiPreheatCurrent', fiPreheatCurrent)
print('hvLoadMa', hvLoadMa)
if hvIdleKv and hvIdleKv > config['hv']['kV'] + 0.5:
config['var']['hv']['idlePwm'] = config['var']['hv']['idlePwm'] - 1
elif hvIdleKv and hvIdleKv < config['hv']['kV'] - 0.5:
config['var']['hv']['idlePwm'] = config['var']['hv']['idlePwm'] + 1
if config['var']['hv']['idlePwm'] > config['var']['hv']['limitPwm']:
config['var']['hv']['idlePwm'] = config['var']['hv']['limitPwm']
if hvLoadKv and hvLoadKv > config['hv']['kV'] + 0.5:
config['var']['hv']['loadPwm'] = config['var']['hv']['loadPwm'] - 1
elif hvLoadKv and hvLoadKv < config['hv']['kV'] - 0.5:
config['var']['hv']['loadPwm'] = config['var']['hv']['loadPwm'] + 1
if config['var']['hv']['loadPwm'] > config['var']['hv']['limitPwm']:
config['var']['hv']['loadPwm'] = config['var']['hv']['limitPwm']
elif hvLoadKv and pwmDutyRayOn > config['var']['hv']['idlePwm']:
config['var']['hv']['loadPwm'] = pwmDutyRayOn
if fiPreheatCurrent and fiPreheatCurrent > config['hv']['filament']['preheat'] + 50:
config['var']['filament']['preheatPwm'] = config['var']['filament']['preheatPwm'] - 1
elif fiPreheatCurrent and fiPreheatCurrent < config['hv']['filament']['preheat'] - 50:
config['var']['filament']['preheatPwm'] = config['var']['filament']['preheatPwm'] + 1
if config['var']['filament']['preheatPwm'] > config['var']['filament']['limitPwm']:
config['var']['filament']['preheatPwm'] = config['var']['filament']['limitPwm']
if hvLoadMa and hvLoadMa > config['hv']['mA']:
config['var']['filament']['normalPwm'] = filamentLoadDuty - 1
elif hvLoadMa and hvLoadMa < config['hv']['mA'] - 0.03:
config['var']['filament']['normalPwm'] = filamentLoadDuty + 1
if config['var']['filament']['normalPwm'] > config['var']['filament']['limitPwm']:
config['var']['filament']['normalPwm'] = config['var']['filament']['limitPwm']
save_config('var')
print(config['var'])
def main():
global config, hvSwitch, raySwitch, wslock, rayStartTime, wdt, selfTestTime, sysErrorList, himAOverLimitCount, hvTempValue
exitFlag = False
hvStopTime = 0
hvUpdateTime = 0
firstRun = True
try:
load_config()
print(config)
if config['dev']['watchdog_enable']:
wdt = WDT('wdt', 2)
_thread.stack_size(10240)
_thread.start_new_thread(py_server,(ws_cmd_handler,))
mb_init()
delay = 2
count = 0
print("pwm init success!")
print(hvPwm)
print("adc init success!")
time.sleep_ms(100)
while not exitFlag:
if hiMaValue < 0.85:
if himAOverLimitCount > 0:
himAOverLimitCount = himAOverLimitCount - 1
else:
error = {
"hiMaValue" : hiMaValue,
"hvKVValue" : hvKvValue,
"hvPwm" : pwmDuty,
"filamentPwm" : filamentDuty
}
if himAOverLimitCount < 5:
config['var']['filament']['normalPwm'] = config['var']['filament']['normalPwm'] - 10
himAOverLimitCount = himAOverLimitCount + 1
else:
raySwitch = False
hvSwitch = False
hvControl(0)
filament.set_duty(0)
time.sleep_ms(100)
error['type'] = 'maOverLimit'
error['time'] = time.ticks_ms()
if len(sysErrorList) > 5:
sysErrorList.pop(0)
sysErrorList.append(error)
if hvKvValue > 70:
error = {
"hiMaValue" : hiMaValue,
"hvKVValue" : hvKvValue,
"hvPwm" : pwmDuty,
"filamentPwm" : filamentDuty
}
hvSwitch = False
hvControl(0)
filament.set_duty(0)
error['type'] = 'kvOverLimit'
error['time'] = time.time_ms()
sysErrorList.append(error)
time.sleep_ms(100)
if selfTestTime > 0:
raySwitch = False
tim = time.ticks_diff(time.ticks_ms(), selfTestTime)
if tim > 10000:
selfTestTime = 0
hvAdcPoll(10, delay)
if config['hv']['selfTest'] or selfTestTime > 0:
time.sleep_ms(20)
else:
time.sleep_ms(10)
try:
mb_server.process()
except Exception as e:
print('Exception during execution: {}'.format(e))
count = count + 1
if count * delay * 10 > 500:
count = 0
if selfTestTime > 0:
print("selfTestTime: %d" % tim)
#print("pwm: %d %d"%(pwmDuty,filamentDuty))
#print("hv: %d, %.2fkV"%(hvAdcValue, hvKvValue))
#print("hi: %d, %.2fmA"%(hiAdcValue, hiMaValue))
#print("fv: %.2f, fi %d: %.2fA"%(filamentVoltage / 1000, filamentDuty, filamentCurrent / 1000))
#print("xray_ctrl_pin", raySwitchPin.value())
tempVal = tempAdc.average()
hvTempValue = adc2temp(tempVal) * 100
print(tempVal, hvTempValue)
print('\n')
#gc.collect()
#gc.dump_info()
mb_reg_update()
ws_status_update()
if wdt:
wdt.feed()
if config['hv']['selfTest'] or selfTestTime > 0:
if hvSwitch:
hvVarCollect()
filamentVarCollect()
varCheckAndSave()
kV_set = config['hv']['kV']
mA_set = config['hv']['mA']
fi_limit = config['hv']['filament']['limit']
fi_preheat = config['hv']['filament']['preheat']
if hvSwitch:
if hvStopTime > 0:
tim = time.ticks_diff(time.ticks_ms(), hvStopTime)
if tim > 30000: # 30s
selfTestTime = time.ticks_ms()
hvStopTime = 0
if firstRun:
firstRun = False
selfTestTime = time.ticks_ms()
if filaInfo['relay_stat'] != True:
filament.set_relay(True)
time.sleep_ms(20)
if config['hv']['selfTest'] or selfTestTime > 0:
hvControl(kV_set)
else:
hvControlFast(kV_set)
if (not config['hv']['selfTest']) and (selfTestTime == 0):
if config['dev']['xray_ctrl_pin_enable']:
raySwitch = not raySwitchPin.value()
else:
raySwitch = False
if hvStopTime < 1:
hvStopTime = time.ticks_ms()
hvControl(0)
if filaInfo['relay_stat'] != False:
filament.set_relay(False)
if not config['hv']['selfTest'] and rayStartTime > 1 and time.ticks_ms() > rayStartTime + 5000:
raySwitch = False
if raySwitch and hvSwitch:
hvUpdateTime = 0
if config['hv']['selfTest'] or selfTestTime > 0:
filamentControlNormal(mA_set, fi_limit)
else:
if rayStartTime < 1:
#清空平均缓冲区
averageBuffer['hvLoadKv'] = []
averageBuffer['hvLoadMa'] = []
rayStartTime = time.ticks_ms()
filamentControlFast(mA_set)
elif hvSwitch:
if hvUpdateTime < 1:
hvUpdateTime = time.ticks_ms()
if config['hv']['selfTest'] or selfTestTime > 0:
if count % 10 == 0:
filamentPreheat(fi_preheat)
else:
if rayStartTime > 0:
varUpdate()
averageBuffer['hvIdleKv'] = []
averageBuffer['fiPreheatCurrent'] = []
hvControlFast(kV_set)
elif hvUpdateTime > 0 and time.ticks_diff(time.ticks_ms(), hvUpdateTime) > 3 * 1000:
hvUpdateTime = time.ticks_ms()
varUpdate()
filamentPreheatFast(fi_preheat)
rayStartTime = 0
else:
hvUpdateTime = 0
rayStartTime = 0
filamentPreheat(fi_preheat)
print("main exit")
except Exception as e:
sys.print_exception(e)
finally:
exitFlag = True
filament.set_duty(0)
filament.set_relay(False)
hvAdc.deinit()
hiAdc.deinit()
hvPwm.deinit()
hvPwmn.deinit()
filament.deinit()
print('exit')
#time.sleep(1)
if __name__ == '__main__':
main()
+834
View File
@@ -0,0 +1,834 @@
import machine
from machine import PWM
from machine import ADC
from machine import Filament
from machine import WDT
from machine import Pin
from machine import Fram
import sys
import time
import _thread
import json
import gc
import os
from webserver import send_ws, send_ws_list, py_server
# ----------------------------------------------------------------------------
from script.umodbus.serial import ModbusRTU
wdt = None
mb_client = None
filaFlag = 0
exitFlag = False
pwmDuty = 0
filament = Filament(3)
filament.init()
filament.set_relay(False)
#PWM
hvPwm = PWM('pwm1', 2, 46000, 0, 50, False)
hvPwmn = PWM('pwm1', 3, 46000, 1023, 50, False)
#ADC
hvAdc = ADC('adc1', 16) # HV Voltage
hiAdc = ADC('adc3', 0) # HV Current
hvAdc.average(50)
hiAdc.average(50)
hvAdcValue = 0
hvKvValue = 0
hvSwitch = False
raySwitch = False
raySwitchPin = Pin(('GPIOC', 6))
raySwitchPin.init(Pin.IN)
rayStartTime = 0
web_socket_list = []
wslock = None
filaInfo = {
'relay_stat' : False,
'vout' : 0,
'iout' : 0,
'vin' : 0,
'iin' : 0
}
hiAdcValue = 0
hiMaValue = 0
filamentCurrent = 0
filamentVoltage = 0
filamentDuty = 0
averageBuffer = {
"hvIdleKv" : [],
"hvLoadKv" : [],
"fiPreheatCurrent": [],
"hvLoadMa": []
}
config = {
"dev" : {
"code" : "1#HVS",
"id" : "12345",
},
"mqtt" : {},
"hv" : {
"kV": 70,
"filament": {
"preheat": 300,
"limit": 1200
},
"mA": 0.7,
"xrayAdjustTime": 600,
"selfTest" : False
},
"var" : {
"hv" : {
"idlePwm" : 200,
"loadPwm" : 320,
"limitPwm" : 450
},
"filament" : {
"preheatPwm": 50,
"limitPwm": 300,
"normalPwm": 260
}
}
}
def averageBufferPut(key, value):
global averageBuffer
if key in averageBuffer:
averageBuffer[key].append(value)
if len(averageBuffer[key]) > 20:
averageBuffer[key].pop(0)
def averageBufferGetAverage(key, n):
global averageBuffer
if key in averageBuffer:
values = averageBuffer[key]
if len(values) < n:
return None
n = min(n, len(values)) # 取 n 和当前数组长度的最小值
if n == 0:
return 0 # 如果没有值,则返回 0
average = sum(values[:n]) / n
return average
return None
def mb_control_cb(reg_type, address, val):
global hvSwitch, raySwitch
print('control',reg_type,address,val)
for value in val:
if address == 0:
hvSwitch = value == True
mb_client.set_coil(7 - 0, hvSwitch)
print("hvSwitch:",hvSwitch)
elif address == 1:
if value == True:
print('alarm clear')
mb_client.set_coil(7 - 1, False)
elif address == 2:
if config['dev']['xray_ctrl_pin_enable']:
return
raySwitch = value == True
mb_client.set_coil(7 - 2, raySwitch)
print("raySwitch:",raySwitch)
address += 1
def mb_param_cb(reg_type, address, val):
print('param',reg_type,address,val)
for value in val:
if address == 0:
config['hv'].update({'kV' : value / 100.0})
elif address == 1:
config['hv'].update({'mA' : value / 1000.0})
elif address == 2:
config['hv']['filament'].update({'limit' : value})
elif address == 3:
config['hv']['filament'].update({'preheat' : value})
address += 1
save_config('hv')
mb_register_definitions = {
"COILS": {
"control": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0],
"on_set_cb": mb_control_cb
}
},
"HREGS": {
"params": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0],
"on_set_cb": mb_param_cb
}
},
"ISTS": {
"status": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0]
}
},
"IREGS": {
"input": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0]
}
}
}
def load_config():
global config
config_path = "/config/hv.json"
try:
with open(config_path, 'r') as f:
config['hv'] = json.load(f)
except OSError as e:
print("文件操作错误:", e)
except ValueError as e:
print("JSON 解析错误:", e)
config_path = "/config/mqtt.json"
try:
with open(config_path, 'r') as f:
config['mqtt'] = json.load(f)
except OSError as e:
print("文件操作错误:", e)
except ValueError as e:
print("JSON 解析错误:", e)
config_path = "/config/dev.json"
try:
with open(config_path, 'r') as f:
config['dev'] = json.load(f)
except OSError as e:
print("文件操作错误:", e)
except ValueError as e:
print("JSON 解析错误:", e)
config_path = "/config/var.json"
var = None
try:
varBuf = Fram.read(0, 512)
var = json.loads(varBuf)
except ValueError as e:
print("JSON 解析错误:", e)
var = None
if var:
config['var'] = var
with open(config_path, 'w') as f:
json.dump(var, f)
print('write var.json', var)
else:
try:
with open(config_path, 'r') as f:
config['var'] = json.load(f)
Fram.write(0, json.dumps(config['var']).encode() + b'\x00')
except OSError as e:
print("文件操作错误:", e)
except ValueError as e:
print("JSON 解析错误:", e)
def save_config(config_type):
if config_type == 'var':
Fram.write(0, json.dumps(config['var']).encode() + b'\x00')
return
try:
data = config[config_type]
config_path = "/config/" + config_type + '.json'
with open(config_path, 'w') as f:
f.write(json.dumps(data))
except OSError as e:
print("文件操作错误:", e)
def mb_init():
global mb_client
print("mb_init...")
mb_client = ModbusRTU(addr = config['dev']['mb_addr'],baudrate=115200,uart_id=4,ctrl_pin=-2)
mb_client.setup_registers(registers=mb_register_definitions)
mb_client.set_hreg(0, [
int(config['hv']['kV'] * 100),
int(config['hv']['mA'] * 1000),
int(config['hv']['filament']['limit']),
int(config['hv']['filament']['preheat']),
])
mb_client.set_coil(0, hvSwitch)
mb_client.set_coil(2, raySwitch)
# if not mb_client.get_bound_status():
# mb_client.bind(local_ip='0.0.0.0', local_port=502)
# print("start mb tcp server")
def hvAdc2kV(hv):
return hv / 65535.0 * 3.0 * 3 * 10
def hiAdc2mA(hi):
return hi / 65535.0 * 3.0 * 3 / 4.4
#read hv voltage and current, num times, and return the average value
def hvAdcRead(num, delay):
global filaInfo
sumHv = 0
sumHi = 0
for i in range(num):
sumHv += hvAdc.read()
sumHi += hiAdc.read()
time.sleep_ms(delay)
sumHv /= num
sumHi /= num
filaInfo = filament.read()
fv = filaInfo['vout']
fi = filaInfo['iout']
return sumHv, sumHi, fv, fi
def hvAdcRead():
global filaInfo
sumHv = hvAdc.average()
sumHi = hiAdc.average()
filaInfo = filament.read()
fv = filaInfo['vout']
fi = filaInfo['iout']
return sumHv, sumHi, fv, fi
def hvAdcPoll(count, delay):
global hvAdcValue, hvKvValue, hiAdcValue, hiMaValue
global filamentDuty, filamentCurrent, filamentVoltage
hv, hi, fv, fi = hvAdcRead()
hvAdcValue = hv
hiAdcValue = hi
hvKvValue = hvAdc2kV(hv)
hiMaValue = hiAdc2mA(hi)
filamentCurrent = fi
filamentVoltage = fv
# control the filament current
def filamentPreheat(fiPreheat):
global filamentCurrent, filamentVoltage, filamentDuty, filaFlag
tmpDuty = filamentDuty
fi = filamentCurrent
if fi > fiPreheat + 100:
tmpDuty -= 2
elif fi > fiPreheat + 50:
tmpDuty -= 1
elif fi < fiPreheat - 100:
tmpDuty += 2
elif fi < fiPreheat - 50:
tmpDuty += 1
if tmpDuty < 0:
tmpDuty = 0
elif tmpDuty > 750:
tmpDuty = 750
filament.set_duty(tmpDuty)
filamentDuty = tmpDuty
# print('preheat', fiPreheat, tmpDuty)
# control the filament current
def filamentPreheatFast(fiPreheat):
global filamentCurrent, filamentVoltage, filamentDuty, filaFlag
if fiPreheat < 0.01:
tmpDuty = 0
filament.set_duty(tmpDuty)
filamentDuty = tmpDuty
return
tmpDuty = config['var']['filament']['preheatPwm']
fi = filamentCurrent
if tmpDuty > config['var']['filament']['limitPwm']:
tmpDuty = config['var']['filament']['limitPwm']
if filamentDuty != tmpDuty:
filament.set_duty(tmpDuty)
filamentDuty = tmpDuty
# print('preheat', fiPreheat, tmpDuty)
else:
averageBufferPut('fiPreheatCurrent', filamentCurrent)
# control the filament current
def filamentControlNormal(hiAim, fiLimit):
global filamentCurrent, filamentVoltage, filamentDuty, filaFlag
tmpDuty = filamentDuty
hi = hiMaValue
fi = filamentCurrent
delta = (hi - hiAim) * 1000
if delta < 0:
val = -delta
else:
val = delta
daDelta = 0
if val > 200:
daDelta = 2
elif val > 40:
daDelta = 1
elif val > 10:
daDelta = 0
elif val > 5:
daDelta = 0
else:
daDelta = 0
if fi > fiLimit:
tmpDuty -= 10
elif delta > 0:
tmpDuty -= daDelta
elif delta < 0:
tmpDuty += daDelta
if tmpDuty < 0:
tmpDuty = 0
elif tmpDuty > config['var']['filament']['limitPwm']:
tmpDuty = config['var']['filament']['limitPwm']
filament.set_duty(tmpDuty)
# filament.set_duty(0)
filamentDuty = tmpDuty
# control the filament current
def filamentControlFast():
global filamentCurrent, filamentVoltage, filamentDuty, filaFlag
aimDuty = config['var']['filament']['normalPwm']
if filamentDuty == aimDuty:
averageBufferPut('hvLoadMa', hiMaValue)
return
tmpDuty = filamentDuty
if tmpDuty < aimDuty:
tmpDuty = tmpDuty + aimDuty / 5
if tmpDuty > aimDuty:
tmpDuty = aimDuty
if tmpDuty > config['var']['filament']['limitPwm']:
tmpDuty = config['var']['filament']['limitPwm']
filamentDuty = int(tmpDuty)
filament.set_duty(filamentDuty)
print('filamentDuty adjust', filamentDuty)
# filament.set_duty(0)
def hvControlFast(hvAim):
global pwmDuty, rayStartTime
if not hvSwitch:
pwmDuty = 0
hvPwm.duty(pwmDuty)
hvPwmn.duty(1023 - pwmDuty)
return
if not raySwitch:
tmpDuty = config['var']['hv']['idlePwm']
if pwmDuty > tmpDuty:
pwmDuty = tmpDuty
hvPwm.duty(pwmDuty)
hvPwmn.duty(1023 - pwmDuty)
print("hv adjust to idle", pwmDuty)
elif pwmDuty < tmpDuty:
pwmDuty = pwmDuty + 3
if pwmDuty > tmpDuty:
pwmDuty = tmpDuty
hvPwm.duty(pwmDuty)
hvPwmn.duty(1023 - pwmDuty)
print("hv adjust to idle", pwmDuty)
else:
averageBufferPut('hvIdleKv', hvKvValue)
return
if pwmDuty == config['var']['hv']['loadPwm']:
averageBufferPut('hvLoadKv', hvKvValue)
deltaTime = 0
if rayStartTime > 1:
now = time.ticks_ms()
deltaTime = time.ticks_diff(now, rayStartTime)
if deltaTime > config['hv']['xrayAdjustTime']:
return
if pwmDuty == config['var']['hv']['loadPwm']:
return
if hvKvValue > 69:
return
tmpDuty = pwmDuty
if hvKvValue >= config['hv']['kV']:
tmpDuty = tmpDuty + 1
elif hvAim > hvKvValue + 3:
tmpDuty = tmpDuty + 3
else:
tmpDuty = tmpDuty + 2
if tmpDuty > config['var']['hv']['loadPwm']:
tmpDuty = config['var']['hv']['loadPwm']
pwmDuty = tmpDuty
hvPwm.duty(pwmDuty)
hvPwmn.duty(1023 - pwmDuty)
print("hv adjust", deltaTime, pwmDuty)
def hvControl(hvAim):
global pwmDuty, rayStartTime
if not hvSwitch:
pwmDuty = 0
hvPwm.duty(pwmDuty)
hvPwmn.duty(1023 - pwmDuty)
return
hv = hvKvValue
pwmVal = pwmDuty
delta = (hv - hvAim) * 1000
if delta < 0:
val = -delta
else:
val = delta
pwmDelta = 0
if val > 20000:
pwmDelta = 3
elif val > 10000:
pwmDelta = 2
elif val > 1000:
pwmDelta = 1
else:
pwmDelta = 0
if delta > 0:
pwmVal -= pwmDelta
elif delta < 0:
pwmVal += pwmDelta
if pwmVal < 0:
pwmVal = 0
elif pwmVal > 450:
pwmVal = 450
#pwmVal = 30
hvPwm.duty(pwmVal)
hvPwmn.duty(1023 - pwmVal)
if pwmDuty != pwmVal:
pwmDuty = pwmVal
#print("pwm:%d,%d"%(pwmDelta, pwmDuty))
def mb_reg_update():
mb_client.set_ireg(0, [
int(hvKvValue * 100),
int(hiMaValue * 1000),
int(filamentCurrent),
])
def ws_status_update():
status = {
'param' : {
'kV' : config['hv']['kV'],
'mA' : config['hv']['mA']
},
'value' : {
'hv' : 'on' if hvSwitch else 'off',
'xray' : 'on' if raySwitch else 'off',
'kV' : hvKvValue,
'mA' : hiMaValue,
'fV' : filamentVoltage / 1000,
'fI' : filamentCurrent / 1000,
'Vin' : filaInfo['vin'] / 1000,
'Iin' : filaInfo['iin'] / 1000
}
}
send_ws_list('/dev/status/hsv', status)
def ws_cmd_handler(ws, payload):
global hvSwitch, raySwitch
obj = json.loads(payload)
msg = obj['message']
dev_id = msg['device_id']
dev_code = msg['device_code']
cmd = msg['command']
if cmd == 'set_params':
value = msg['value']
if 'filament' in value:
config['hv']['filament'].update(value['filament'])
del value['filament']
config['hv'].update(value)
mb_client.set_hreg(0, [
int(config['hv']['kV']),
int(config['hv']['mA'] * 1000),
int(config['hv']['filament']['limit']),
int(config['hv']['filament']['preheat']),
])
print(config['hv'])
save_config('hv')
elif cmd == 'get_params':
msg = config['dev']
msg['command'] = cmd
msg['value'] = config['hv']
send_ws(ws, '/dev/response/hsv', msg)
elif cmd == 'hv_control':
hvSwitch = msg['value'] == 'on'
mb_client.set_coil(7 - 0, hvSwitch)
print("hvSwitch:",hvSwitch)
send_ws(ws, '/dev/response/hsv', msg)
elif cmd == 'ray_control':
if config['dev']['xray_ctrl_pin_enable']:
return
raySwitch = msg['value'] == 'on'
mb_client.set_coil(7 - 2, raySwitch)
print("raySwitch:",raySwitch)
send_ws(ws, '/dev/response/hsv', msg)
elif cmd == 'get_var':
msg['command'] = cmd
msg['value'] = config['var']
send_ws(ws, '/dev/response/hsv', msg)
elif cmd == 'set_var':
value = msg['value']
config['var'].update(value)
save_config('var')
def hvVarCollect():
if not hvSwitch:
return
if raySwitch:
aim = config['hv']['mA']
if hiMaValue < aim * 1.05 and hiMaValue > aim * 0.95:
config['var']['hv']['loadPwm'] = pwmDuty
else:
aim = config['hv']['kV']
if hvKvValue < aim + 1 and hvKvValue > aim - 1:
config['var']['hv']['idlePwm'] = pwmDuty
def filamentVarCollect():
if not hvSwitch:
return
if raySwitch:
aim = config['hv']['mA']
if hiMaValue < aim * 1.05 and hiMaValue > aim * 0.95:
config['var']['filament']['normalPwm'] = filamentDuty
else:
aim = config['hv']['filament']['preheat']
if filamentCurrent < aim + 50 and filamentCurrent > aim - 50:
config['var']['filament']['preheatPwm'] = filamentDuty
def varCheckAndSave():
config_path = "/config/var.json"
saveFlag = False
try:
with open(config_path, 'r') as f:
conf = json.load(f)
if config['var']['hv']['loadPwm'] != conf['hv']['loadPwm'] or \
config['var']['hv']['idlePwm'] != conf['hv']['idlePwm'] or \
config['var']['filament']['normalPwm'] != conf['filament']['normalPwm'] or \
config['var']['filament']['preheatPwm'] != conf['filament']['preheatPwm']:
saveFlag = True
except OSError as e:
print("文件操作错误:", e)
except ValueError as e:
print("JSON 解析错误:", e)
if saveFlag:
save_config('var')
def varUpdate():
hvIdleKv = averageBufferGetAverage('hvIdleKv', 10)
hvLoadKv = averageBufferGetAverage('hvLoadKv', 10)
if hvIdleKv and hvIdleKv > config['hv']['kV']:
config['var']['hv']['idlePwm'] = config['var']['hv']['idlePwm'] - 1
elif hvIdleKv and hvIdleKv < config['hv']['kV'] - 0.5:
config['var']['hv']['idlePwm'] = config['var']['hv']['idlePwm'] + 1
if hvLoadKv and hvLoadKv > config['hv']['kV']:
config['var']['hv']['loadPwm'] = config['var']['hv']['loadPwm'] - 1
elif hvLoadKv and hvLoadKv < config['hv']['kV'] - 0.5:
config['var']['hv']['loadPwm'] = config['var']['hv']['loadPwm'] + 1
fiPreheatCurrent = averageBufferGetAverage('fiPreheatCurrent', 10)
if fiPreheatCurrent and fiPreheatCurrent > config['hv']['filament']['preheat'] + 50:
config['var']['filament']['preheatPwm'] = config['var']['filament']['preheatPwm'] - 1
elif fiPreheatCurrent and fiPreheatCurrent < config['hv']['filament']['preheat'] - 50:
config['var']['filament']['preheatPwm'] = config['var']['filament']['preheatPwm'] + 1
hvLoadMa = averageBufferGetAverage('hvLoadMa', 10)
if hvLoadMa and hvLoadMa > config['hv']['mA']:
config['var']['filament']['normalPwm'] = config['var']['filament']['normalPwm'] - 1
elif hvLoadMa and hvLoadMa < config['hv']['mA'] - 0.03:
config['var']['filament']['normalPwm'] = config['var']['filament']['normalPwm'] + 1
save_config('var')
print(config['var'])
def main():
global config, exitFlag, hvSwitch, raySwitch, wslock, rayStartTime, wdt
xrayIdleFlag = False
try:
load_config()
print(config)
if config['dev']['watchdog_enable']:
wdt = WDT('wdt', 2)
_thread.start_new_thread(py_server,(ws_cmd_handler,))
mb_init()
delay = 2
count = 0
print("pwm init success!")
print(hvPwm)
print("adc init success!")
time.sleep_ms(100)
while not exitFlag:
hvAdcPoll(10, delay)
if config['hv']['selfTest']:
time.sleep_ms(20)
else:
time.sleep_ms(10)
try:
mb_client.process()
except Exception as e:
print('Exception during execution: {}'.format(e))
count = count + 1
if count * delay * 10 > 200:
count = 0
print("pwm: %d %d"%(pwmDuty,filamentDuty))
print("hv: %d, %.2fkV"%(hvAdcValue, hvKvValue))
print("hi: %d, %.2fmA"%(hiAdcValue, hiMaValue))
print("fv: %.2f, fi %d: %.2fA"%(filamentVoltage / 1000, filamentDuty, filamentCurrent / 1000))
print("xray_ctrl_pin", raySwitchPin.value())
print('\n')
gc.collect()
#gc.dump_info()
mb_reg_update()
ws_status_update()
if wdt:
wdt.feed()
if config['hv']['selfTest']:
if hvSwitch:
hvVarCollect()
filamentVarCollect()
varCheckAndSave()
kV_set = config['hv']['kV']
mA_set = config['hv']['mA']
fi_limit = config['hv']['filament']['limit']
fi_preheat = config['hv']['filament']['preheat']
if hvSwitch:
if filaInfo['relay_stat'] != True:
filament.set_relay(True)
time.sleep_ms(20)
if config['hv']['selfTest']:
hvControl(kV_set)
else:
hvControlFast(kV_set)
else:
hvControl(0)
if filaInfo['relay_stat'] != False:
filament.set_relay(False)
if config['dev']['xray_ctrl_pin_enable']:
raySwitch = not raySwitchPin.value()
if not hvSwitch:
raySwitch = False
if raySwitch and hvSwitch:
if config['hv']['selfTest']:
filamentControlNormal(mA_set, fi_limit)
else:
if rayStartTime < 1:
#清空平均缓冲区
averageBuffer['hvLoadKv'] = []
averageBuffer['hvLoadMa'] = []
rayStartTime = time.ticks_ms()
filamentControlFast()
elif hvSwitch:
if config['hv']['selfTest']:
if count % 10 == 0:
filamentPreheat(fi_preheat)
else:
if rayStartTime > 0:
averageBuffer['hvIdleKv'] = []
averageBuffer['fiPreheatCurrent'] = []
hvControlFast(kV_set)
xrayIdleFlag = True
filamentPreheatFast(fi_preheat)
rayStartTime = 0
if xrayIdleFlag:
xrayIdleFlag = False
varUpdate()
else:
rayStartTime = 0
filamentPreheatFast(0)
print("main exit")
except Exception as e:
sys.print_exception(e)
finally:
exitFlag = True
filament.set_duty(0)
filament.set_relay(False)
hvAdc.deinit()
hiAdc.deinit()
hvPwm.deinit()
hvPwmn.deinit()
filament.deinit()
print('exit')
time.sleep(1)
if __name__ == '__main__':
main()
+8
View File
@@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
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.
+377
View File
@@ -0,0 +1,377 @@
<h3>
<p align="center">
Also check out the new ESP32 MPY-Jama free IDE and the latest MicroWebSrv2 below:
</p>
</h3>
<p align="center">
<a href="https://github.com/jczic/ESP32-MPY-Jama"><img src="https://github.com/jczic/ESP32-MPY-Jama/raw/master/img/ESP32%20MPY-Jama%20NEW.png" alt="New microWebSrv2" width="350" valign="middle"></a>                  
<a href="https://github.com/jczic/MicroWebSrv2"><img src="microWebSrv2.png" alt="New microWebSrv2" width="350" valign="middle"></a>
</p>
---
<br />
### MicroWebSrv is a micro HTTP Web server that supports WebSockets, html/python language templating and routing handlers, for MicroPython (principally used on ESP32 and [Pycom](http://www.pycom.io) modules. Now supports all variants of [Pyboard D-series](https://store.micropython.org/category/pyboard%20D-series) from the makers of Micropython)
![HC²](hc2.png "HC²")
Very easy to integrate and very light with 3 files only :
- `"microWebSrv.py"` - The Web server
- `"microWebSocket.py"` - The optional support of WebSockets
- `"microWebTemplate.py"` - The optional templating language for **.pyhtml** rendered pages
Mini tuto in video by rdagger68 :
- [https://www.youtube.com/watch?v=xscBwC1SrF4](https://www.youtube.com/watch?v=xscBwC1SrF4)
Simple but effective :
- Use it to embed a cool Web site in yours modules
- Handle GET, POST, ... requests to interract with user and configure options
- Exchange in JSON format on HTTP methods to make an embedded fullREST API
- Serve files on the fly to export any data to the user
- Use routes and variable route handlers
- Play with AjAX to interact speedly with a Web application
- Make it a captive portal simply
- Use WebSockets for fast and powerful data exchange
- Make html/python files for rendering more efficient web pages
### Using *microWebSrv* main class :
| Name | Function |
| - | - |
| Constructor | `mws = MicroWebSrv(routeHandlers=None, port=80, bindIP='0.0.0.0', webPath="/flash/www")` |
| Start Web server | `mws.Start(threaded=True)` |
| Stop Web server | `mws.Stop()` |
| Check if Web server is running | `mws.IsStarted()` |
| Set URL location for not found page | `mws.SetNotFoundPageUrl(url=None)` |
| Get mime type from file extention | `mws.GetMimeTypeFromFilename(filename)` |
| Get handler function from route | `(routeHandler, routeArgs) = mws.GetRouteHandler(resUrl, method)` |
| Callback function to enable and accept WebSockets | `mws.AcceptWebSocketCallback = _acptWS` `_acptWS(webSocket, httpClient) { }` |
| Maximum length of memory allocated to receive WebSockets data (1024 by default) | `mws.MaxWebSocketRecvLen` |
| New thread used for each WebSocket connection (True by default) | `mws.WebSocketThreaded` |
| Escape string to HTML usage | `MicroWebSrv.HTMLEscape(s)` |
### Basic example :
```python
from microWebSrv import MicroWebSrv
mws = MicroWebSrv() # TCP port 80 and files in /flash/www
mws.Start(threaded=True) # Starts server in a new thread
```
### Using as captive portal :
```python
# To intercept all not found queries and redirect it,
mws.SetNotFoundPageUrl("http://my-device.wifi")
```
- Can be used with [MicroDNSSrv](http://microdnssrv.hc2.fr) easily.
### Using route handlers example :
```python
routeHandlers = [
( "relative_url_route_1", "METHOD", handlerFunc_1 ),
( "relative_url_route_2", "METHOD", handlerFunc_2 ),
( ... )
]
```
```python
def handlerFunc_1(httpClient, httpResponse, routeArgs=None) :
print("In HTTP handler 1")
def handlerFunc_2(httpClient, httpResponse, routeArgs=None) :
print("In HTTP handler 2")
```
### Using directly route handlers decorators example :
```python
@MicroWebSrv.route('/get-test')
def handlerFuncGet(httpClient, httpResponse) :
print("In GET-TEST HTTP")
@MicroWebSrv.route('/post-test', 'POST')
def handlerFuncPost(httpClient, httpResponse) :
print("In POST-TEST HTTP")
```
### Using variable routes example :
```python
routeHandlers = [
( "/edit/<testid>/<testpath>", "GET", handlerFuncEdit ),
( ... )
]
def handlerFuncEdit(httpClient, httpResponse, routeArgs) :
print("In EDIT HTTP variable route :")
print(" - testid = %s" % routeArgs['testid'])
print(" - testpath = %s" % routeArgs['testpath'])
```
Or direclty with route handler decorator :
```python
@MicroWebSrv.route('/edit/<testid>/<testpath>')
def handlerFuncEdit(httpClient, httpResponse, routeArgs) :
print("In EDIT HTTP variable route :")
print(" - testid = %s" % routeArgs['testid'])
print(" - testpath = %s" % routeArgs['testpath'])
```
### Using *httpClient* class in a route handler function :
| Name | Function |
| - | - |
| Get MicroWebSrv class | `httpClient.GetServer()` |
| Get client address as tuple | `httpClient.GetAddr()` |
| Get client IP address | `httpClient.GetIPAddr()` |
| Get client TCP port | `httpClient.GetPort()` |
| Get client request method | `httpClient.GetRequestMethod()` |
| Get client request total path | `httpClient.GetRequestTotalPath()` |
| Get client request ressource path | `httpClient.GetRequestPath()` |
| Get client request query string | `httpClient.GetRequestQueryString()` |
| Get client request query parameters as list | `httpClient.GetRequestQueryParams()` |
| Get client request headers as list | `httpClient.GetRequestHeaders()` |
| Get client request content type | `httpClient.GetRequestContentType()` |
| Get client request content length | `httpClient.GetRequestContentLength()` |
| Get client request content | `httpClient.ReadRequestContent(size=None)` |
| Get client request form data as list | `httpClient.ReadRequestPostedFormData()` |
| Get client request as JSON object | `httpClient.ReadRequestContentAsJSON()` |
### Using *httpResponse* class in a route handler function :
| Name | Function |
| - | - |
| Write switching protocols response | `httpResponse.WriteSwitchProto(upgrade, headers=None)` |
| Write generic response | `httpResponse.WriteResponse(code, headers, contentType, contentCharset, content)` |
| Write PyHTML rendered response page | `httpResponse.WriteResponsePyHTMLFile(filepath, headers=None, vars=None)` |
| Write file directly as response | `httpResponse.WriteResponseFile(filepath, contentType=None, headers=None)` |
| Write attached file as response | `httpResponse.WriteResponseFileAttachment(filepath, attachmentName, headers=None)` |
| Write OK response | `httpResponse.WriteResponseOk(headers=None, contentType=None, contentCharset=None, content=None)` |
| Write JSON object as OK response | `httpResponse.WriteResponseJSONOk(obj=None, headers=None)` |
| Write redirect response | `httpResponse.WriteResponseRedirect(location)` |
| Write error response | `httpResponse.WriteResponseError(code)` |
| Write JSON object as error response | `httpResponse.WriteResponseJSONError(code, obj=None)` |
| Write bad request response | `httpResponse.WriteResponseBadRequest()` |
| Write forbidden response | `httpResponse.WriteResponseForbidden()` |
| Write not found response | `httpResponse.WriteResponseNotFound()` |
| Write method not allowed response | `httpResponse.WriteResponseMethodNotAllowed()` |
| Write internal server error response | `httpResponse.WriteResponseInternalServerError()` |
| Write not implemented response | `httpResponse.WriteResponseNotImplemented()` |
### Using route handler function example :
```python
def _httpHandlerTestPost(httpClient, httpResponse) :
formData = httpClient.ReadRequestPostedFormData()
firstname = formData["firstname"]
lastname = formData["lastname"]
content = """\
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>TEST POST</title>
</head>
<body>
<h1>TEST POST</h1>
Firstname = %s<br />
Lastname = %s<br />
</body>
</html>
""" % ( MicroWebSrv.HTMLEscape(firstname),
MicroWebSrv.HTMLEscape(lastname) )
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )
```
### Known mime types (content types) :
| File extension | Mime type |
| - | - |
| .txt | text/plain |
| .htm | text/html |
| .html | text/html |
| .css | text/css |
| .csv | text/csv |
| .js | application/javascript |
| .xml | application/xml |
| .xhtml | application/xhtml+xml |
| .json | application/json |
| .zip | application/zip |
| .pdf | application/pdf |
| .ts | application/typescript |
| .woff | font/woff |
| .woff2 | font/woff2 |
| .ttf | font/ttf |
| .otf | font/otf |
| .jpg | image/jpeg |
| .jpeg | image/jpeg |
| .png | image/png |
| .gif | image/gif |
| .svg | image/svg+xml |
| .ico | image/x-icon |
### Default index pages order (for http://hostname/) :
| Filename |
| - |
| index.pyhtml |
| index.html |
| index.htm |
| default.pyhtml |
| default.html |
| default.htm |
### Using optional module *microWebSocket* to connect WebSockets :
- File `"microWebSocket.py"` must be present to activate WebSockets support
### Enable and accept WebSockets :
```python
from microWebSrv import MicroWebSrv
mws = MicroWebSrv() # TCP port 80 and files in /flash/www
mws.MaxWebSocketRecvLen = 256 # Default is set to 1024
mws.WebSocketThreaded = False # WebSockets without new threads
mws.AcceptWebSocketCallback = _acceptWebSocketCallback # Function to receive WebSockets
mws.Start(threaded=True) # Starts server in a new thread
```
| Name | Function |
| - | - |
| Callback function to receive text message | `ws.RecvTextCallback = func(webSocket, msg)` |
| Callback function to receive binary data | `ws.RecvBinaryCallback = func(webSocket, data)` |
| Callback function when connection was closed | `ws.ClosedCallback = func(webSocket)` |
| Send a text message | `ws.SendText(msg)` |
| Send a binary message | `ws.SendBinary(data)` |
| Check connection state | `ws.IsClosed()` |
| Close the connection | `ws.Close()` |
### Basic example of callback functions :
```python
def _acceptWebSocketCallback(webSocket, httpClient) :
print("WS ACCEPT")
webSocket.RecvTextCallback = _recvTextCallback
webSocket.RecvBinaryCallback = _recvBinaryCallback
webSocket.ClosedCallback = _closedCallback
def _recvTextCallback(webSocket, msg) :
print("WS RECV TEXT : %s" % msg)
webSocket.SendText("Reply for %s" % msg)
def _recvBinaryCallback(webSocket, data) :
print("WS RECV DATA : %s" % data)
def _closedCallback(webSocket) :
print("WS CLOSED")
```
### Using optional module *microWebTemplate* for *.pyhtml* rendered pages :
- File `"microWebTemplate.py"` must be present to activate **.pyhtml** pages
- Pages will be rendered in HTML with integrated MicroPython code
| Instruction | Schema |
| - | - |
| PY | `{{ py }}` *MicroPython code* `{{ end }}` |
| IF | `{{ if` *MicroPython condition* `}}` *html bloc* `{{ end }}` |
| ELIF | `{{ elif` *MicroPython condition* `}}` *html bloc* `{{ end }}` |
| ELSE | `{{ else }}` *html bloc* `{{ end }}` |
| FOR | `{{ for` *identifier* `in` *MicroPython iterator* `}}` *html bloc* `{{ end }}` |
| INCLUDE | `{{ include` *pyhtml_filename* `}}` |
| ?   | `{{` *MicroPython expression* `}}` |
### Using {{ py }} :
```python
{{ py }}
import machine
from utime import sleep
test = 123
def testFunc(x) :
return 2 * x
{{ end }}
```
### Using {{ if ... }} :
```python
{{ if testFunc(5) <= 3 }}
<span>titi</span>
{{ elif testFunc(10) >= 15 }}
<span>tata</span>
{{ else }}
<span>I like the number {{ test }} !</span>
{{ end }}
```
### Using {{ for ... }} :
```python
{{ for toto in range(testFunc(3)) }}
<div>toto x 10 equal {{ toto * 10 }}</div>
<hr />
{{ end }}
```
### Using {{ include ... }} :
```python
{{ include myTemplate.pyhtml }}
```
### Example of a .pyhtml file :
```html
<html>
<head>
<title>TEST PYHTML</title>
</head>
<body>
<h1>BEGIN</h1>
{{ py }}
def _testFunction(x) :
return "IN TEST FUNCTION %s" % x
{{ end }}
<div style="background-color: black; color: white;">
{{ for toto in range(3) }}
This is an HTML test...<br />
TOTO = {{ toto + 1 }} !<br />
{{ for toto2 in range(3) }}
TOTO2 = {{ _testFunction(toto2) }}
{{ end }}
Ok good.<br />
{{ end }}
</div>
{{ _testFunction(100) }}<br />
<br />
{{ if 2+5 < 3 }}
IN IF (1)
{{ elif 10+15 != 25 }}
IN ELIF (2)
{{ elif 10+15 == 25 }}
IN ELIF (3)
{{ else }}
IN ELSE (4)
{{ end }}
</body>
</html>
```
<a name="author"></a>
## :wink: &nbsp;Author
**Jean-Christophe Bos** (:fr:)
- GitHub: *[@jczic](https://github.com/jczic)*
- Email: *<jczic.bos@gmail.com>*
- Profil: *[LinkedIn](https://www.linkedin.com/in/jczic)*
- Music: *[SoundCloud](https://soundcloud.com/jczic/sets/electro-pulse)*
*[Spotify](https://open.spotify.com/album/5fUd57GcAIcdUn9NX3fviG)*
*[YouTube](https://www.youtube.com/playlist?list=PL9CsGuMbcLaU02VKS7jtR6LaDNpq7MZEq)*
### By JC`zic for [HC²](https://www.hc2.fr) ;')
*Keep it simple, stupid* :+1:
+2
View File
@@ -0,0 +1,2 @@
show_downloads: true
theme: jekyll-theme-midnight
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

+121
View File
@@ -0,0 +1,121 @@
from microWebSrv import MicroWebSrv
# ----------------------------------------------------------------------------
@MicroWebSrv.route('/test')
def _httpHandlerTestGet(httpClient, httpResponse) :
content = """\
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8" />
<title>TEST GET</title>
</head>
<body>
<h1>TEST GET</h1>
Client IP address = %s
<br />
<form action="/test" method="post" accept-charset="ISO-8859-1">
First name: <input type="text" name="firstname"><br />
Last name: <input type="text" name="lastname"><br />
<input type="submit" value="Submit">
</form>
</body>
</html>
""" % httpClient.GetIPAddr()
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )
@MicroWebSrv.route('/test', 'POST')
def _httpHandlerTestPost(httpClient, httpResponse) :
formData = httpClient.ReadRequestPostedFormData()
firstname = formData["firstname"]
lastname = formData["lastname"]
content = """\
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8" />
<title>TEST POST</title>
</head>
<body>
<h1>TEST POST</h1>
Firstname = %s<br />
Lastname = %s<br />
</body>
</html>
""" % ( MicroWebSrv.HTMLEscape(firstname),
MicroWebSrv.HTMLEscape(lastname) )
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )
@MicroWebSrv.route('/edit/<index>') # <IP>/edit/123 -> args['index']=123
@MicroWebSrv.route('/edit/<index>/abc/<foo>') # <IP>/edit/123/abc/bar -> args['index']=123 args['foo']='bar'
@MicroWebSrv.route('/edit') # <IP>/edit -> args={}
def _httpHandlerEditWithArgs(httpClient, httpResponse, args={}) :
content = """\
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8" />
<title>TEST EDIT</title>
</head>
<body>
"""
content += "<h1>EDIT item with {} variable arguments</h1>"\
.format(len(args))
if 'index' in args :
content += "<p>index = {}</p>".format(args['index'])
if 'foo' in args :
content += "<p>foo = {}</p>".format(args['foo'])
content += """
</body>
</html>
"""
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )
# ----------------------------------------------------------------------------
def _acceptWebSocketCallback(webSocket, httpClient) :
print("WS ACCEPT")
webSocket.RecvTextCallback = _recvTextCallback
webSocket.RecvBinaryCallback = _recvBinaryCallback
webSocket.ClosedCallback = _closedCallback
def _recvTextCallback(webSocket, msg) :
print("WS RECV TEXT : %s" % msg)
webSocket.SendText("Reply for %s" % msg)
def _recvBinaryCallback(webSocket, data) :
print("WS RECV DATA : %s" % data)
def _closedCallback(webSocket) :
print("WS CLOSED")
# ----------------------------------------------------------------------------
#routeHandlers = [
# ( "/test", "GET", _httpHandlerTestGet ),
# ( "/test", "POST", _httpHandlerTestPost )
#]
srv = MicroWebSrv(webPath='/web_root/web_admin/')
srv.MaxWebSocketRecvLen = 256
srv.WebSocketThreaded = False
srv.AcceptWebSocketCallback = _acceptWebSocketCallback
srv.Start()
# ----------------------------------------------------------------------------
+284
View File
@@ -0,0 +1,284 @@
"""
The MIT License (MIT)
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from hashlib import sha1
from binascii import b2a_base64
from struct import pack
from _thread import start_new_thread, allocate_lock
import gc
class MicroWebSocket :
# ============================================================================
# ===( Constants )============================================================
# ============================================================================
_handshakeSign = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
_opContFrame = 0x0
_opTextFrame = 0x1
_opBinFrame = 0x2
_opCloseFrame = 0x8
_opPingFrame = 0x9
_opPongFrame = 0xA
_msgTypeText = 1
_msgTypeBin = 2
# ============================================================================
# ===( Utils )===============================================================
# ============================================================================
@staticmethod
def _tryAllocByteArray(size) :
for x in range(10) :
try :
gc.collect()
return bytearray(size)
except :
pass
return None
# ----------------------------------------------------------------------------
@staticmethod
def _tryStartThread(func, args=()) :
for x in range(10) :
try :
gc.collect()
start_new_thread(func, args)
return True
except :
global _mws_thread_id
try :
_mws_thread_id += 1
except :
_mws_thread_id = 0
try :
start_new_thread('MWS_THREAD_%s' % _mws_thread_id, func, args)
return True
except :
pass
return False
# ============================================================================
# ===( Constructor )==========================================================
# ============================================================================
def __init__(self, socket, httpClient, httpResponse, maxRecvLen, threaded, acceptCallback) :
self._socket = socket
self._httpCli = httpClient
self._closed = True
self._lock = allocate_lock()
self.RecvTextCallback = None
self.RecvBinaryCallback = None
self.ClosedCallback = None
if hasattr(socket, 'read'): # MicroPython
self._socketfile = self._socket
else: # CPython
self._socketfile = self._socket.makefile('rwb')
if self._handshake(httpResponse) :
self._ctrlBuf = MicroWebSocket._tryAllocByteArray(0x7D)
self._msgBuf = MicroWebSocket._tryAllocByteArray(maxRecvLen)
if self._ctrlBuf and self._msgBuf :
self._msgType = None
self._msgLen = 0
if threaded :
if MicroWebSocket._tryStartThread(self._wsProcess, (acceptCallback, )) :
return
else :
self._wsProcess(acceptCallback)
return
print("MicroWebSocket : Out of memory on new WebSocket connection.")
try :
if self._socketfile is not self._socket:
self._socketfile.close()
self._socket.close()
except :
pass
# ============================================================================
# ===( Functions )============================================================
# ============================================================================
def _handshake(self, httpResponse) :
try :
key = self._httpCli.GetRequestHeaders().get('sec-websocket-key', None)
if key :
key += self._handshakeSign
r = sha1(key.encode()).digest()
r = b2a_base64(r).decode().strip()
httpResponse.WriteSwitchProto("websocket", { "Sec-WebSocket-Accept" : r })
return True
except :
pass
return False
# ----------------------------------------------------------------------------
def _wsProcess(self, acceptCallback) :
self._socket.settimeout(3600)
self._closed = False
try :
acceptCallback(self, self._httpCli)
except Exception as ex :
print("MicroWebSocket : Error on accept callback (%s)." % str(ex))
while not self._closed :
if not self._receiveFrame() :
self.Close()
if self.ClosedCallback :
try :
self.ClosedCallback(self)
except Exception as ex :
print("MicroWebSocket : Error on closed callback (%s)." % str(ex))
# ----------------------------------------------------------------------------
def _receiveFrame(self) :
try :
b = self._socketfile.read(2)
if not b or len(b) != 2 :
return False
fin = b[0] & 0x80 > 0
opcode = b[0] & 0x0F
masked = b[1] & 0x80 > 0
length = b[1] & 0x7F
if opcode == self._opContFrame and not self._msgType :
return False
elif opcode == self._opTextFrame :
self._msgType = self._msgTypeText
elif opcode == self._opBinFrame :
self._msgType = self._msgTypeBin
if length == 0x7E :
b = self._socketfile.read(2)
if not b or len(b) != 2 :
return False
length = (b[0] << 8) + b[1]
elif length == 0x7F :
return False
mask = self._socketfile.read(4) if masked else None
if masked and (not mask or len(mask) != 4) :
return False
if opcode == self._opContFrame or \
opcode == self._opTextFrame or \
opcode == self._opBinFrame :
if length > 0 :
buf = memoryview(self._msgBuf)[self._msgLen:]
if length > len(buf) :
return False
x = self._socketfile.readinto(buf[0:length])
if x != length :
return False
if masked :
for i in range(length) :
idx = self._msgLen + i
self._msgBuf[idx] ^= mask[i%4]
self._msgLen += length
if fin :
b = bytes(memoryview(self._msgBuf)[:self._msgLen])
if self._msgType == self._msgTypeText :
if self.RecvTextCallback :
try :
self.RecvTextCallback(self, b.decode())
except Exception as ex :
print("MicroWebSocket : Error on recv text callback (%s)." % str(ex))
else :
if self.RecvBinaryCallback :
try :
self.RecvBinaryCallback(self, b)
except Exception as ex :
print("MicroWebSocket : Error on recv binary callback (%s)." % str(ex))
self._msgType = None
self._msgLen = 0
else :
return False
elif opcode == self._opPingFrame :
if length > len(self._ctrlBuf) :
return False
if length > 0 :
x = self._socketfile.readinto(self._ctrlBuf[0:length])
if x != length :
return False
pingData = memoryview(self._ctrlBuf)[:length]
else :
pingData = None
self._sendFrame(self._opPongFrame, pingData)
elif opcode == self._opCloseFrame :
self.Close()
except :
return False
return True
# ----------------------------------------------------------------------------
def _sendFrame(self, opcode, data=None, fin=True) :
if not self._closed and opcode >= 0x00 and opcode <= 0x0F :
dataLen = 0 if not data else len(data)
if dataLen <= 0xFFFF :
b1 = (0x80 | opcode) if fin else opcode
b2 = 0x7E if dataLen >= 0x7E else dataLen
self._lock.acquire()
try :
if self._socketfile.write(pack('>BB', b1, b2)) == 2 :
if dataLen > 0 :
if dataLen >= 0x7E :
self._socketfile.write(pack('>H', dataLen))
ret = self._socketfile.write(data) == dataLen
else :
ret = True
if self._socketfile is not self._socket :
self._socketfile.flush() # CPython needs flush to continue protocol
self._lock.release()
return ret
except :
pass
self._lock.release()
return False
# ----------------------------------------------------------------------------
def SendText(self, msg) :
return self._sendFrame(self._opTextFrame, msg.encode())
# ----------------------------------------------------------------------------
def SendBinary(self, data) :
return self._sendFrame(self._opBinFrame, data)
# ----------------------------------------------------------------------------
def IsClosed(self) :
return self._closed
# ----------------------------------------------------------------------------
def Close(self) :
if not self._closed :
try :
self._sendFrame(self._opCloseFrame)
if self._socketfile is not self._socket:
self._socketfile.close()
self._socket.close()
self._closed = True
except :
pass
# ============================================================================
# ============================================================================
# ============================================================================
+881
View File
@@ -0,0 +1,881 @@
"""
The MIT License (MIT)
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from json import loads, dumps
from os import stat
from _thread import start_new_thread
import socket
import gc
import re
try :
from microWebTemplate import MicroWebTemplate
except :
pass
try :
from microWebSocket import MicroWebSocket
except :
print("MicroWebSrv: MicroWebSocket module not found, WebSocket support disabled")
pass
class MicroWebSrvRoute :
def __init__(self, route, method, func, routeArgNames, routeRegex) :
self.route = route
self.method = method
self.func = func
self.routeArgNames = routeArgNames
self.routeRegex = routeRegex
class MicroWebSrv :
# ============================================================================
# ===( Constants )============================================================
# ============================================================================
_indexPages = [
"index.pyhtml",
"index.html",
"index.htm",
"default.pyhtml",
"default.html",
"default.htm"
]
_mimeTypes = {
".txt" : "text/plain",
".htm" : "text/html",
".html" : "text/html",
".css" : "text/css",
".csv" : "text/csv",
".js" : "application/javascript",
".xml" : "application/xml",
".xhtml" : "application/xhtml+xml",
".json" : "application/json",
".zip" : "application/zip",
".pdf" : "application/pdf",
".ts" : "application/typescript",
".woff" : "font/woff",
".woff2" : "font/woff2",
".ttf" : "font/ttf",
".otf" : "font/otf",
".jpg" : "image/jpeg",
".jpeg" : "image/jpeg",
".png" : "image/png",
".gif" : "image/gif",
".svg" : "image/svg+xml",
".ico" : "image/x-icon"
}
_html_escape_chars = {
"&" : "&amp;",
'"' : "&quot;",
"'" : "&apos;",
">" : "&gt;",
"<" : "&lt;"
}
_pyhtmlPagesExt = '.pyhtml'
# ============================================================================
# ===( Class globals )=======================================================
# ============================================================================
_docoratedRouteHandlers = []
# ============================================================================
# ===( Utils )===============================================================
# ============================================================================
@classmethod
def route(cls, url, method='GET'):
""" Adds a route handler function to the routing list """
def route_decorator(func):
item = (url, method, func)
cls._docoratedRouteHandlers.append(item)
return func
return route_decorator
# ----------------------------------------------------------------------------
@staticmethod
def HTMLEscape(s) :
return ''.join(MicroWebSrv._html_escape_chars.get(c, c) for c in s)
# ----------------------------------------------------------------------------
@staticmethod
def _startThread(func, args=()) :
try :
start_new_thread(func, args)
except :
global _mwsrv_thread_id
try :
_mwsrv_thread_id += 1
except :
_mwsrv_thread_id = 0
try :
start_new_thread('MWSRV_THREAD_%s' % _mwsrv_thread_id, func, args)
except :
return False
return True
# ----------------------------------------------------------------------------
@staticmethod
def _unquote(s) :
r = str(s).split('%')
try :
b = r[0].encode()
for i in range(1, len(r)) :
try :
b += bytes([int(r[i][:2], 16)]) + r[i][2:].encode()
except :
b += b'%' + r[i].encode()
return b.decode('UTF-8')
except :
return str(s)
# ------------------------------------------------------------------------------
@staticmethod
def _unquote_plus(s) :
return MicroWebSrv._unquote(s.replace('+', ' '))
# ------------------------------------------------------------------------------
@staticmethod
def _fileExists(path) :
try :
stat(path)
return True
except :
return False
# ----------------------------------------------------------------------------
@staticmethod
def _isPyHTMLFile(filename) :
return filename.lower().endswith(MicroWebSrv._pyhtmlPagesExt)
# ============================================================================
# ===( Constructor )==========================================================
# ============================================================================
def __init__( self,
routeHandlers = [],
port = 80,
bindIP = '0.0.0.0',
webPath = "/flash/www" ) :
self._srvAddr = (bindIP, port)
self._webPath = webPath
self._notFoundUrl = None
self._started = False
self.MaxWebSocketRecvLen = 1024
self.WebSocketThreaded = True
self.AcceptWebSocketCallback = None
self.LetCacheStaticContentLevel = 2
self._routeHandlers = []
routeHandlers += self._docoratedRouteHandlers
for route, method, func in routeHandlers :
routeParts = route.split('/')
# -> ['', 'users', '<uID>', 'addresses', '<addrID>', 'test', '<anotherID>']
routeArgNames = []
routeRegex = ''
for s in routeParts :
if s.startswith('<') and s.endswith('>') :
routeArgNames.append(s[1:-1])
routeRegex += '/(\\w*)'
elif s :
routeRegex += '/' + s
routeRegex += '$'
# -> '/users/(\w*)/addresses/(\w*)/test/(\w*)$'
routeRegex = re.compile(routeRegex)
self._routeHandlers.append(MicroWebSrvRoute(route, method, func, routeArgNames, routeRegex))
# ============================================================================
# ===( Server Process )=======================================================
# ============================================================================
def _serverProcess(self) :
self._started = True
while True :
try :
client, cliAddr = self._server.accept()
except Exception as ex :
if ex.args and ex.args[0] == 113 :
break
continue
self._client(self, client, cliAddr)
self._started = False
# ============================================================================
# ===( Functions )============================================================
# ============================================================================
def Start(self, threaded=False) :
if not self._started :
self._server = socket.socket()
self._server.setsockopt( socket.SOL_SOCKET,
socket.SO_REUSEADDR,
1 )
self._server.bind(self._srvAddr)
self._server.listen(16)
if threaded :
MicroWebSrv._startThread(self._serverProcess)
else :
self._serverProcess()
# ----------------------------------------------------------------------------
def Stop(self) :
if self._started :
self._server.close()
# ----------------------------------------------------------------------------
def IsStarted(self) :
return self._started
# ----------------------------------------------------------------------------
def SetNotFoundPageUrl(self, url=None) :
self._notFoundUrl = url
# ----------------------------------------------------------------------------
def GetMimeTypeFromFilename(self, filename) :
filename = filename.lower()
for ext in self._mimeTypes :
if filename.endswith(ext) :
return self._mimeTypes[ext]
return None
# ----------------------------------------------------------------------------
def GetRouteHandler(self, resUrl, method) :
if self._routeHandlers :
#resUrl = resUrl.upper()
if resUrl.endswith('/') :
resUrl = resUrl[:-1]
method = method.upper()
for rh in self._routeHandlers :
if rh.method == method :
m = rh.routeRegex.match(resUrl)
if m : # found matching route?
if rh.routeArgNames :
routeArgs = {}
for i, name in enumerate(rh.routeArgNames) :
value = m.group(i+1)
try :
value = int(value)
except :
pass
routeArgs[name] = value
return (rh.func, routeArgs)
else :
return (rh.func, None)
return (None, None)
# ----------------------------------------------------------------------------
def _physPathFromURLPath(self, urlPath) :
if urlPath == '/' :
for idxPage in self._indexPages :
physPath = self._webPath + '/' + idxPage
if MicroWebSrv._fileExists(physPath) :
return physPath
else :
physPath = self._webPath + urlPath.replace('../', '/')
if MicroWebSrv._fileExists(physPath) :
return physPath
return None
# ============================================================================
# ===( Class Client )========================================================
# ============================================================================
class _client :
# ------------------------------------------------------------------------
def __init__(self, microWebSrv, socket, addr) :
socket.settimeout(2)
self._microWebSrv = microWebSrv
self._socket = socket
self._addr = addr
self._method = None
self._path = None
self._httpVer = None
self._resPath = "/"
self._queryString = ""
self._queryParams = { }
self._headers = { }
self._contentType = None
self._contentLength = 0
if hasattr(socket, 'readline'): # MicroPython
self._socketfile = self._socket
else: # CPython
self._socketfile = self._socket.makefile('rwb')
self._processRequest()
# ------------------------------------------------------------------------
def _processRequest(self) :
try :
response = MicroWebSrv._response(self)
if self._parseFirstLine(response) :
if self._parseHeader(response) :
upg = self._getConnUpgrade()
if not upg :
routeHandler, routeArgs = self._microWebSrv.GetRouteHandler(self._resPath, self._method)
if routeHandler :
try :
if routeArgs is not None:
routeHandler(self, response, routeArgs)
else :
routeHandler(self, response)
except Exception as ex :
print('MicroWebSrv handler exception:\r\n - In route %s %s\r\n - %s' % (self._method, self._resPath, ex))
raise ex
elif self._method.upper() == "GET" :
filepath = self._microWebSrv._physPathFromURLPath(self._resPath)
if filepath :
if MicroWebSrv._isPyHTMLFile(filepath) :
response.WriteResponsePyHTMLFile(filepath)
else :
contentType = self._microWebSrv.GetMimeTypeFromFilename(filepath)
if contentType :
if self._microWebSrv.LetCacheStaticContentLevel > 0 :
if self._microWebSrv.LetCacheStaticContentLevel > 1 and \
'if-modified-since' in self._headers :
response.WriteResponseNotModified()
else:
headers = { 'Last-Modified' : 'Fri, 1 Jan 2018 23:42:00 GMT', \
'Cache-Control' : 'max-age=315360000' }
response.WriteResponseFile(filepath, contentType, headers)
else :
response.WriteResponseFile(filepath, contentType)
else :
response.WriteResponseForbidden()
else :
response.WriteResponseNotFound()
else :
response.WriteResponseMethodNotAllowed()
elif upg == 'websocket' and 'MicroWebSocket' in globals() \
and self._microWebSrv.AcceptWebSocketCallback :
MicroWebSocket( socket = self._socket,
httpClient = self,
httpResponse = response,
maxRecvLen = self._microWebSrv.MaxWebSocketRecvLen,
threaded = self._microWebSrv.WebSocketThreaded,
acceptCallback = self._microWebSrv.AcceptWebSocketCallback )
return
else :
response.WriteResponseNotImplemented()
else :
response.WriteResponseBadRequest()
except :
response.WriteResponseInternalServerError()
try :
if self._socketfile is not self._socket:
self._socketfile.close()
self._socket.close()
except :
pass
# ------------------------------------------------------------------------
def _parseFirstLine(self, response) :
try :
elements = self._socketfile.readline().decode().strip().split()
if len(elements) == 3 :
self._method = elements[0].upper()
self._path = elements[1]
self._httpVer = elements[2].upper()
elements = self._path.split('?', 1)
if len(elements) > 0 :
self._resPath = MicroWebSrv._unquote_plus(elements[0])
if len(elements) > 1 :
self._queryString = elements[1]
elements = self._queryString.split('&')
for s in elements :
param = s.split('=', 1)
if len(param) > 0 :
value = MicroWebSrv._unquote(param[1]) if len(param) > 1 else ''
self._queryParams[MicroWebSrv._unquote(param[0])] = value
return True
except :
pass
return False
# ------------------------------------------------------------------------
def _parseHeader(self, response) :
while True :
elements = self._socketfile.readline().decode().strip().split(':', 1)
if len(elements) == 2 :
self._headers[elements[0].strip().lower()] = elements[1].strip()
elif len(elements) == 1 and len(elements[0]) == 0 :
if self._method == 'POST' or self._method == 'PUT' :
self._contentType = self._headers.get("content-type", None)
self._contentLength = int(self._headers.get("content-length", 0))
return True
else :
return False
# ------------------------------------------------------------------------
def _getConnUpgrade(self) :
if 'upgrade' in self._headers.get('connection', '').lower() :
return self._headers.get('upgrade', '').lower()
return None
# ------------------------------------------------------------------------
def GetServer(self) :
return self._microWebSrv
# ------------------------------------------------------------------------
def GetAddr(self) :
return self._addr
# ------------------------------------------------------------------------
def GetIPAddr(self) :
return self._addr[0]
# ------------------------------------------------------------------------
def GetPort(self) :
return self._addr[1]
# ------------------------------------------------------------------------
def GetRequestMethod(self) :
return self._method
# ------------------------------------------------------------------------
def GetRequestTotalPath(self) :
return self._path
# ------------------------------------------------------------------------
def GetRequestPath(self) :
return self._resPath
# ------------------------------------------------------------------------
def GetRequestQueryString(self) :
return self._queryString
# ------------------------------------------------------------------------
def GetRequestQueryParams(self) :
return self._queryParams
# ------------------------------------------------------------------------
def GetRequestHeaders(self) :
return self._headers
# ------------------------------------------------------------------------
def GetRequestContentType(self) :
return self._contentType
# ------------------------------------------------------------------------
def GetRequestContentLength(self) :
return self._contentLength
# ------------------------------------------------------------------------
def ReadRequestContent(self, size=None) :
if size is None :
size = self._contentLength
if size > 0 :
try :
return self._socketfile.read(size)
except :
pass
return b''
# ------------------------------------------------------------------------
def ReadRequestPostedFormData(self) :
res = { }
data = self.ReadRequestContent()
if data :
elements = data.decode().split('&')
for s in elements :
param = s.split('=', 1)
if len(param) > 0 :
value = MicroWebSrv._unquote_plus(param[1]) if len(param) > 1 else ''
res[MicroWebSrv._unquote_plus(param[0])] = value
return res
# ------------------------------------------------------------------------
def ReadRequestContentAsJSON(self) :
data = self.ReadRequestContent()
if data :
try :
return loads(data.decode())
except :
pass
return None
# ============================================================================
# ===( Class Response )======================================================
# ============================================================================
class _response :
# ------------------------------------------------------------------------
def __init__(self, client) :
self._client = client
# ------------------------------------------------------------------------
def _write(self, data, strEncoding='ISO-8859-1') :
if data :
if type(data) == str :
data = data.encode(strEncoding)
data = memoryview(data)
while data :
n = self._client._socketfile.write(data)
if n is None :
return False
data = data[n:]
return True
return False
# ------------------------------------------------------------------------
def _writeFirstLine(self, code) :
reason = self._responseCodes.get(code, ('Unknown reason', ))[0]
return self._write("HTTP/1.1 %s %s\r\n" % (code, reason))
# ------------------------------------------------------------------------
def _writeHeader(self, name, value) :
return self._write("%s: %s\r\n" % (name, value))
# ------------------------------------------------------------------------
def _writeContentTypeHeader(self, contentType, charset=None) :
if contentType :
ct = contentType \
+ (("; charset=%s" % charset) if charset else "")
else :
ct = "application/octet-stream"
self._writeHeader("Content-Type", ct)
# ------------------------------------------------------------------------
def _writeServerHeader(self) :
self._writeHeader("Server", "MicroWebSrv by JC`zic")
# ------------------------------------------------------------------------
def _writeEndHeader(self) :
return self._write("\r\n")
# ------------------------------------------------------------------------
def _writeBeforeContent(self, code, headers, contentType, contentCharset, contentLength) :
self._writeFirstLine(code)
if isinstance(headers, dict) :
for header in headers :
self._writeHeader(header, headers[header])
if contentLength > 0 :
self._writeContentTypeHeader(contentType, contentCharset)
self._writeHeader("Content-Length", contentLength)
self._writeServerHeader()
self._writeHeader("Connection", "close")
self._writeEndHeader()
# ------------------------------------------------------------------------
def WriteSwitchProto(self, upgrade, headers=None) :
self._writeFirstLine(101)
self._writeHeader("Connection", "Upgrade")
self._writeHeader("Upgrade", upgrade)
if isinstance(headers, dict) :
for header in headers :
self._writeHeader(header, headers[header])
self._writeServerHeader()
self._writeEndHeader()
if self._client._socketfile is not self._client._socket :
self._client._socketfile.flush() # CPython needs flush to continue protocol
# ------------------------------------------------------------------------
def WriteResponse(self, code, headers, contentType, contentCharset, content) :
try :
if content :
if type(content) == str :
content = content.encode(contentCharset)
contentLength = len(content)
else :
contentLength = 0
self._writeBeforeContent(code, headers, contentType, contentCharset, contentLength)
if content :
return self._write(content)
return True
except :
return False
# ------------------------------------------------------------------------
def WriteResponsePyHTMLFile(self, filepath, headers=None, vars=None) :
if 'MicroWebTemplate' in globals() :
with open(filepath, 'r') as file :
code = file.read()
mWebTmpl = MicroWebTemplate(code, escapeStrFunc=MicroWebSrv.HTMLEscape, filepath=filepath)
try :
tmplResult = mWebTmpl.Execute(None, vars)
return self.WriteResponse(200, headers, "text/html", "UTF-8", tmplResult)
except Exception as ex :
return self.WriteResponse( 500,
None,
"text/html",
"UTF-8",
self._execErrCtnTmpl % {
'module' : 'PyHTML',
'message' : str(ex)
} )
return self.WriteResponseNotImplemented()
# ------------------------------------------------------------------------
def WriteResponseFile(self, filepath, contentType=None, headers=None) :
try :
size = stat(filepath)[6]
if size > 0 :
with open(filepath, 'rb') as file :
self._writeBeforeContent(200, headers, contentType, None, size)
try :
buf = bytearray(1024)
while size > 0 :
x = file.readinto(buf)
if x < len(buf) :
buf = memoryview(buf)[:x]
if not self._write(buf) :
return False
size -= x
return True
except :
self.WriteResponseInternalServerError()
return False
except :
pass
self.WriteResponseNotFound()
return False
# ------------------------------------------------------------------------
def WriteResponseFileAttachment(self, filepath, attachmentName, headers=None) :
if not isinstance(headers, dict) :
headers = { }
headers["Content-Disposition"] = "attachment; filename=\"%s\"" % attachmentName
return self.WriteResponseFile(filepath, None, headers)
# ------------------------------------------------------------------------
def WriteResponseOk(self, headers=None, contentType=None, contentCharset=None, content=None) :
return self.WriteResponse(200, headers, contentType, contentCharset, content)
# ------------------------------------------------------------------------
def WriteResponseJSONOk(self, obj=None, headers=None) :
return self.WriteResponse(200, headers, "application/json", "UTF-8", dumps(obj))
# ------------------------------------------------------------------------
def WriteResponseRedirect(self, location) :
headers = { "Location" : location }
return self.WriteResponse(302, headers, None, None, None)
# ------------------------------------------------------------------------
def WriteResponseError(self, code) :
responseCode = self._responseCodes.get(code, ('Unknown reason', ''))
return self.WriteResponse( code,
None,
"text/html",
"UTF-8",
self._errCtnTmpl % {
'code' : code,
'reason' : responseCode[0],
'message' : responseCode[1]
} )
# ------------------------------------------------------------------------
def WriteResponseJSONError(self, code, obj=None) :
return self.WriteResponse( code,
None,
"application/json",
"UTF-8",
dumps(obj if obj else { }) )
# ------------------------------------------------------------------------
def WriteResponseNotModified(self) :
return self.WriteResponseError(304)
# ------------------------------------------------------------------------
def WriteResponseBadRequest(self) :
return self.WriteResponseError(400)
# ------------------------------------------------------------------------
def WriteResponseForbidden(self) :
return self.WriteResponseError(403)
# ------------------------------------------------------------------------
def WriteResponseNotFound(self) :
if self._client._microWebSrv._notFoundUrl :
self.WriteResponseRedirect(self._client._microWebSrv._notFoundUrl)
else :
return self.WriteResponseError(404)
# ------------------------------------------------------------------------
def WriteResponseMethodNotAllowed(self) :
return self.WriteResponseError(405)
# ------------------------------------------------------------------------
def WriteResponseInternalServerError(self) :
return self.WriteResponseError(500)
# ------------------------------------------------------------------------
def WriteResponseNotImplemented(self) :
return self.WriteResponseError(501)
# ------------------------------------------------------------------------
def FlashMessage(self, messageText, messageStyle='') :
if 'MicroWebTemplate' in globals() :
MicroWebTemplate.MESSAGE_TEXT = messageText
MicroWebTemplate.MESSAGE_STYLE = messageStyle
# ------------------------------------------------------------------------
_errCtnTmpl = """\
<html>
<head>
<title>Error</title>
</head>
<body>
<h1>%(code)d %(reason)s</h1>
%(message)s
</body>
</html>
"""
# ------------------------------------------------------------------------
_execErrCtnTmpl = """\
<html>
<head>
<title>Page execution error</title>
</head>
<body>
<h1>%(module)s page execution error</h1>
%(message)s
</body>
</html>
"""
# ------------------------------------------------------------------------
_responseCodes = {
100: ('Continue', 'Request received, please continue'),
101: ('Switching Protocols',
'Switching to new protocol; obey Upgrade header'),
200: ('OK', 'Request fulfilled, document follows'),
201: ('Created', 'Document created, URL follows'),
202: ('Accepted',
'Request accepted, processing continues off-line'),
203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
204: ('No Content', 'Request fulfilled, nothing follows'),
205: ('Reset Content', 'Clear input form for further input.'),
206: ('Partial Content', 'Partial content follows.'),
300: ('Multiple Choices',
'Object has several resources -- see URI list'),
301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
302: ('Found', 'Object moved temporarily -- see URI list'),
303: ('See Other', 'Object moved -- see Method and URL list'),
304: ('Not Modified',
'Document has not changed since given time'),
305: ('Use Proxy',
'You must use proxy specified in Location to access this '
'resource.'),
307: ('Temporary Redirect',
'Object moved temporarily -- see URI list'),
400: ('Bad Request',
'Bad request syntax or unsupported method'),
401: ('Unauthorized',
'No permission -- see authorization schemes'),
402: ('Payment Required',
'No payment -- see charging schemes'),
403: ('Forbidden',
'Request forbidden -- authorization will not help'),
404: ('Not Found', 'Nothing matches the given URI'),
405: ('Method Not Allowed',
'Specified method is invalid for this resource.'),
406: ('Not Acceptable', 'URI not available in preferred format.'),
407: ('Proxy Authentication Required', 'You must authenticate with '
'this proxy before proceeding.'),
408: ('Request Timeout', 'Request timed out; try again later.'),
409: ('Conflict', 'Request conflict.'),
410: ('Gone',
'URI no longer exists and has been permanently removed.'),
411: ('Length Required', 'Client must specify Content-Length.'),
412: ('Precondition Failed', 'Precondition in headers is false.'),
413: ('Request Entity Too Large', 'Entity is too large.'),
414: ('Request-URI Too Long', 'URI is too long.'),
415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
416: ('Requested Range Not Satisfiable',
'Cannot satisfy request range.'),
417: ('Expectation Failed',
'Expect condition could not be satisfied.'),
500: ('Internal Server Error', 'Server got itself in trouble'),
501: ('Not Implemented',
'Server does not support this operation'),
502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
503: ('Service Unavailable',
'The server cannot process the request due to a high load'),
504: ('Gateway Timeout',
'The gateway server did not receive a timely response'),
505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
}
# ============================================================================
# ============================================================================
# ============================================================================
Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

+336
View File
@@ -0,0 +1,336 @@
"""
The MIT License (MIT)
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
import re
class MicroWebTemplate :
# ============================================================================
# ===( Constants )============================================================
# ============================================================================
TOKEN_OPEN = '{{'
TOKEN_CLOSE = '}}'
TOKEN_OPEN_LEN = len(TOKEN_OPEN)
TOKEN_CLOSE_LEN = len(TOKEN_CLOSE)
INSTRUCTION_PYTHON = 'py'
INSTRUCTION_IF = 'if'
INSTRUCTION_ELIF = 'elif'
INSTRUCTION_ELSE = 'else'
INSTRUCTION_FOR = 'for'
INSTRUCTION_END = 'end'
INSTRUCTION_INCLUDE = 'include'
MESSAGE_TEXT = ''
MESSAGE_STYLE = ''
# ============================================================================
# ===( Constructor )==========================================================
# ============================================================================
def __init__(self, code, escapeStrFunc=None, filepath='') :
self._code = code
self._escapeStrFunc = escapeStrFunc
self._filepath = filepath
self._pos = 0
self._endPos = len(code)-1
self._line = 1
self._reIdentifier = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$')
self._pyGlobalVars = { }
self._pyLocalVars = { }
self._rendered = ''
self._instructions = {
MicroWebTemplate.INSTRUCTION_PYTHON : self._processInstructionPYTHON,
MicroWebTemplate.INSTRUCTION_IF : self._processInstructionIF,
MicroWebTemplate.INSTRUCTION_ELIF : self._processInstructionELIF,
MicroWebTemplate.INSTRUCTION_ELSE : self._processInstructionELSE,
MicroWebTemplate.INSTRUCTION_FOR : self._processInstructionFOR,
MicroWebTemplate.INSTRUCTION_END : self._processInstructionEND,
MicroWebTemplate.INSTRUCTION_INCLUDE: self._processInstructionINCLUDE,
}
# ============================================================================
# ===( Functions )============================================================
# ============================================================================
def Validate(self, pyGlobalVars=None, pyLocalVars=None) :
try :
self._parseCode(pyGlobalVars, pyLocalVars, execute=False)
return None
except Exception as ex :
return str(ex)
# ----------------------------------------------------------------------------
def Execute(self, pyGlobalVars=None, pyLocalVars=None) :
try :
self._parseCode(pyGlobalVars, pyLocalVars, execute=True)
return self._rendered
except Exception as ex :
raise Exception(str(ex))
# ============================================================================
# ===( Utils )===============================================================
# ============================================================================
def _parseCode(self, pyGlobalVars, pyLocalVars, execute) :
if pyGlobalVars:
self._pyGlobalVars.update(pyGlobalVars)
if pyLocalVars:
self._pyLocalVars.update(pyLocalVars)
self._pyLocalVars['MESSAGE_TEXT'] = MicroWebTemplate.MESSAGE_TEXT
self._pyLocalVars['MESSAGE_STYLE'] = MicroWebTemplate.MESSAGE_STYLE
self._rendered = ''
newTokenToProcess = self._parseBloc(execute)
if newTokenToProcess is not None :
raise Exception( '"%s" instruction is not valid here (line %s)'
% (newTokenToProcess, self._line) )
MicroWebTemplate.MESSAGE_TEXT = ''
MicroWebTemplate.MESSAGE_STYLE = ''
# ----------------------------------------------------------------------------
def _parseBloc(self, execute) :
while self._pos <= self._endPos :
c = self._code[self._pos]
if c == MicroWebTemplate.TOKEN_OPEN[0] and \
self._code[ self._pos : self._pos + MicroWebTemplate.TOKEN_OPEN_LEN ] == MicroWebTemplate.TOKEN_OPEN :
self._pos += MicroWebTemplate.TOKEN_OPEN_LEN
tokenContent = ''
x = self._pos
while True :
if x > self._endPos :
raise Exception("%s is missing (line %s)" % (MicroWebTemplate.TOKEN_CLOSE, self._line))
c = self._code[x]
if c == MicroWebTemplate.TOKEN_CLOSE[0] and \
self._code[ x : x + MicroWebTemplate.TOKEN_CLOSE_LEN ] == MicroWebTemplate.TOKEN_CLOSE :
self._pos = x + MicroWebTemplate.TOKEN_CLOSE_LEN
break
elif c == '\n' :
self._line += 1
tokenContent += c
x += 1
newTokenToProcess = self._processToken(tokenContent, execute)
if newTokenToProcess is not None :
return newTokenToProcess
continue
elif c == '\n' :
self._line += 1
if execute :
self._rendered += c
self._pos += 1
return None
# ----------------------------------------------------------------------------
def _processToken(self, tokenContent, execute) :
tokenContent = tokenContent.strip()
parts = tokenContent.split(' ', 1)
instructName = parts[0].strip()
instructBody = parts[1].strip() if len(parts) > 1 else None
if len(instructName) == 0 :
raise Exception( '"%s %s" : instruction is missing (line %s)'
% (MicroWebTemplate.TOKEN_OPEN, MicroWebTemplate.TOKEN_CLOSE, self._line) )
newTokenToProcess = None
if instructName in self._instructions :
newTokenToProcess = self._instructions[instructName](instructBody, execute)
elif execute :
try :
s = str( eval( tokenContent,
self._pyGlobalVars,
self._pyLocalVars ) )
if (self._escapeStrFunc is not None) :
self._rendered += self._escapeStrFunc(s)
else :
self._rendered += s
except Exception as ex :
raise Exception('%s (line %s)' % (str(ex), self._line))
return newTokenToProcess
# ----------------------------------------------------------------------------
def _processInstructionPYTHON(self, instructionBody, execute) :
if instructionBody is not None :
raise Exception( 'Instruction "%s" is invalid (line %s)'
% (MicroWebTemplate.INSTRUCTION_PYTHON, self._line) )
pyCode = ''
while True :
if self._pos > self._endPos :
raise Exception( '"%s" instruction is missing (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
c = self._code[self._pos]
if c == MicroWebTemplate.TOKEN_OPEN[0] and \
self._code[ self._pos : self._pos + MicroWebTemplate.TOKEN_OPEN_LEN ] == MicroWebTemplate.TOKEN_OPEN :
self._pos += MicroWebTemplate.TOKEN_OPEN_LEN
tokenContent = ''
x = self._pos
while True :
if x > self._endPos :
raise Exception("%s is missing (line %s)" % (MicroWebTemplate.TOKEN_CLOSE, self._line))
c = self._code[x]
if c == MicroWebTemplate.TOKEN_CLOSE[0] and \
self._code[ x : x + MicroWebTemplate.TOKEN_CLOSE_LEN ] == MicroWebTemplate.TOKEN_CLOSE :
self._pos = x + MicroWebTemplate.TOKEN_CLOSE_LEN
break
elif c == '\n' :
self._line += 1
tokenContent += c
x += 1
tokenContent = tokenContent.strip()
if tokenContent == MicroWebTemplate.INSTRUCTION_END :
break
raise Exception( '"%s" is a bad instruction in a python bloc (line %s)'
% (tokenContent, self._line) )
elif c == '\n' :
self._line += 1
if execute :
pyCode += c
self._pos += 1
if execute :
lines = pyCode.split('\n')
indent = ''
for line in lines :
if len(line.strip()) > 0 :
for c in line :
if c == ' ' or c == '\t' :
indent += c
else :
break
break
pyCode = ''
for line in lines :
if line.find(indent) == 0 :
line = line[len(indent):]
pyCode += line + '\n'
try :
exec(pyCode, self._pyGlobalVars, self._pyLocalVars)
except Exception as ex :
raise Exception('%s (line %s)' % (str(ex), self._line))
return None
# ----------------------------------------------------------------------------
def _processInstructionIF(self, instructionBody, execute) :
if instructionBody is not None :
if execute :
try :
if (' ' not in instructionBody) and \
('=' not in instructionBody) and \
('<' not in instructionBody) and \
('>' not in instructionBody) and \
(instructionBody not in self._pyGlobalVars) and \
(instructionBody not in self._pyLocalVars):
result = False
else:
result = bool(eval(instructionBody, self._pyGlobalVars, self._pyLocalVars))
except Exception as ex :
raise Exception('%s (line %s)' % (str(ex), self._line))
else :
result = False
newTokenToProcess = self._parseBloc(execute and result)
if newTokenToProcess is not None :
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
return None
elif newTokenToProcess == MicroWebTemplate.INSTRUCTION_ELSE :
newTokenToProcess = self._parseBloc(execute and not result)
if newTokenToProcess is not None :
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
return None
raise Exception( '"%s" instruction waited (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s" instruction is missing (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
elif newTokenToProcess == MicroWebTemplate.INSTRUCTION_ELIF :
self._processInstructionIF(self._elifInstructionBody, execute and not result)
return None
raise Exception( '"%s" instruction waited (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s" instruction is missing (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
% (MicroWebTemplate.INSTRUCTION_IF, self._line) )
# ----------------------------------------------------------------------------
def _processInstructionELIF(self, instructionBody, execute) :
if instructionBody is None :
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
% (MicroWebTemplate.INSTRUCTION_ELIF, self._line) )
self._elifInstructionBody = instructionBody
return MicroWebTemplate.INSTRUCTION_ELIF
# ----------------------------------------------------------------------------
def _processInstructionELSE(self, instructionBody, execute) :
if instructionBody is not None :
raise Exception( 'Instruction "%s" is invalid (line %s)'
% (MicroWebTemplate.INSTRUCTION_ELSE, self._line) )
return MicroWebTemplate.INSTRUCTION_ELSE
# ----------------------------------------------------------------------------
def _processInstructionFOR(self, instructionBody, execute) :
if instructionBody is not None :
parts = instructionBody.split(' ', 1)
identifier = parts[0].strip()
if self._reIdentifier.match(identifier) is not None and len(parts) > 1 :
parts = parts[1].strip().split(' ', 1)
if parts[0] == 'in' and len(parts) > 1 :
expression = parts[1].strip()
newTokenToProcess = None
beforePos = self._pos
if execute :
try :
result = eval(expression, self._pyGlobalVars, self._pyLocalVars)
except :
raise Exception('%s (line %s)' % (str(expression), self._line))
if execute and len(result) > 0 :
for x in result :
self._pyLocalVars[identifier] = x
self._pos = beforePos
newTokenToProcess = self._parseBloc(True)
if newTokenToProcess != MicroWebTemplate.INSTRUCTION_END :
break
else :
newTokenToProcess = self._parseBloc(False)
if newTokenToProcess is not None :
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
return None
raise Exception( '"%s" instruction waited (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s" instruction is missing (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s %s" is an invalid syntax'
% (MicroWebTemplate.INSTRUCTION_FOR, instructionBody) )
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
% (MicroWebTemplate.INSTRUCTION_FOR, self._line) )
# ----------------------------------------------------------------------------
def _processInstructionEND(self, instructionBody, execute) :
if instructionBody is not None :
raise Exception( 'Instruction "%s" is invalid (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
return MicroWebTemplate.INSTRUCTION_END
# ----------------------------------------------------------------------------
def _processInstructionINCLUDE(self, instructionBody, execute) :
if not instructionBody :
raise Exception( '"%s" alone is an incomplete syntax (line %s)' % (MicroWebTemplate.INSTRUCTION_INCLUDE, self._line) )
filename = instructionBody.replace('"','').replace("'",'').strip()
idx = self._filepath.rindex('/')
if idx >= 0 :
filename = self._filepath[:idx+1] + filename
with open(filename, 'r') as file :
includeCode = file.read()
self._code = self._code[:self._pos] + includeCode + self._code[self._pos:]
self._endPos += len(includeCode)
# ============================================================================
# ============================================================================
# ============================================================================
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

+28
View File
@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang=fr>
<head>
<meta charset="UTF-8" />
<title>Page de test MicroWebSrv</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Page de test MicroWebSrv</h1>
<h2>Hello !</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget ligula quis libero mollis dapibus. Suspendisse potenti. Nullam facilisis neque et sem. Proin placerat adipiscing urna. Aenean sollicitudin. Mauris lorem erat, fringilla quis, sagittis a, varius sed, nunc. Pellentesque ligula. Nullam egestas eleifend turpis. Vivamus ac sapien. Sed venenatis, ligula ut scelerisque vehicula, erat tellus euismod ipsum, eget faucibus tortor arcu et lectus. Vivamus vel purus. Fusce dignissim tortor quis diam elementum fermentum. Mauris eleifend lorem vel arcu. Vivamus tempus faucibus lectus. Curabitur volutpat ornare mi. Curabitur ac libero. Sed eu elit ac metus egestas iaculis.
</p>
<br />
<hr />
<br />
<div style="text-align: center">
<img src="pdf.png" />
<p>
Afficher « <a href="test.pdf">un fichier PDF</a> »
</p>
</div>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

+36
View File
@@ -0,0 +1,36 @@
html, body {
margin: 0;
padding: 0;
}
body {
background-color: white;
font-family: Verdana, sans-serif;
font-size: 100%;
}
h1 {
font-size: 200%;
color: navy;
text-align: center;
}
h2 {
font-size: 150%;
color: red;
padding-left: 15px;
}
p,ul,li,td {
color: black;
}
a:link {
color: green;
text-decoration: underline;
}
a:visited {
color: gray;
}
a:hover {
color: red;
text-decoration: none;
}
a:active, a:focus {
color: red;
}
Binary file not shown.
+34
View File
@@ -0,0 +1,34 @@
<html>
<head>
<title>TEST</title>
</head>
<body>
<h1>BEGIN</h1>
{{ py }}
def _testFunction(x) :
return "IN TEST FUNCTION %s" % x
{{ end }}
<div style="background-color: black; color: white;">
{{ for toto in range(3) }}
This is an HTML test...<br />
TOTO = {{ toto + 1 }} !<br />
{{ for toto2 in range(3) }}
TOTO2 = {{ _testFunction(toto2) }}
{{ end }}
Ok good.<br />
{{ end }}
</div>
{{ _testFunction(100) }}<br />
<br />
{{ if 2+5 < 3 }}
IN IF (1)
{{ elif 10+15 != 25 }}
IN ELIF (2)
{{ elif 10+15 == 25 }}
IN ELIF (3)
{{ else }}
IN ELSE (4)
{{ end }}
<h1>JC :')</h1>
</body>
</html>
+78
View File
@@ -0,0 +1,78 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>MicroWebSocket Test</title>
</head>
<script language="javascript">
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket()
{
var wsUri = "ws://" + window.location.hostname;
writeToScreen("Connection to " + wsUri + "...")
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen (evt) };
websocket.onclose = function(evt) { onClose (evt) };
websocket.onmessage = function(evt) { onMessage (evt) };
websocket.onerror = function(evt) { onError (evt) };
}
function onOpen(evt)
{
writeToScreen("<strong>-- CONNECTED --</strong>");
SendMsg("Hello world :)");
SendMsg("This is a WebSocket test");
SendMsg("(with a text frame encoded in UTF-8)");
setTimeout( function() { websocket.close() }, 500 )
}
function onClose(evt)
{
writeToScreen("<strong>-- DISCONNECTED --</strong>");
}
function onMessage(evt)
{
writeToScreen('MSG FROM SERVER : <span style="color: blue;">' + evt.data + '</span>');
}
function onError(evt)
{
writeToScreen('ERROR : <span style="color: red;">' + evt.data + '</span>');
}
function SendMsg(msg)
{
writeToScreen('MSG TO SERVER : <span style="color: green;">' + msg + '</span>');
websocket.send(msg);
}
function writeToScreen(s)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = s;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<body>
<h2>MicroWebSocket Test :</h2>
<div id="output"></div>
</body>
</html>
+5
View File
@@ -0,0 +1,5 @@
rm /download/bootloader.bin
wget http://file.ofs.com/hv/bootloader.bin /download/bootloader.bin
fal probe bootloader
fal erase 0 0x40000
fal write 0 /download/bootloader.bin
+5
View File
@@ -0,0 +1,5 @@
rm /download/firmware.bin
wget http://file.ofs.com/hv/hv_firmware.bin /download/firmware.bin
fal probe ota
fal erase 0 0xC0000
fal write 0 /download/firmware.bin
+69
View File
@@ -0,0 +1,69 @@
import sys
import time
import _thread
import json
import gc
from script.umodbus.serial import ModbusRTU
uart_id = 4
slave_addr = 10 # address on bus as client
client = ModbusRTU(
addr=slave_addr, # address on bus
baudrate=115200, # optional, default 9600
# data_bits=8, # optional, default 8
# stop_bits=1, # optional, default 1
# parity=None, # optional, default None
# ctrl_pin=12, # optional, control DE/RE
uart_id=uart_id # optional, default 1, see port specific documentation
)
register_definitions = {
"COILS": {
"control": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0],
}
},
"HREGS": {
"params": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0],
}
},
"ISTS": {
"status": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0]
}
},
"IREGS": {
"input": {
"register": 0,
"len": 10,
"val": [0,0,0,0,0,0,0,0,0,0]
}
}
}
# use the defined values of each register type provided by register_definitions
client.setup_registers(registers=register_definitions)
print(client)
while True:
try:
result = client.process()
except KeyboardInterrupt:
print('KeyboardInterrupt, stopping RTU client...')
break
except Exception as e:
print('Exception during execution: {}'.format(e))
+3
View File
@@ -0,0 +1,3 @@
fal probe ota
fal erase 0 0xC0000
fal write 0 /download/firmware.bin
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from .version import __version__
+392
View File
@@ -0,0 +1,392 @@
#!/usr/bin/env python
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#
# system packages
import struct
# custom packages
from . import const as Const
from . import functions
# typing not natively supported on MicroPython
from .typing import List, Optional, Tuple, Union
class Request(object):
"""Deconstruct request data received via TCP or Serial"""
def __init__(self, interface, data: bytearray) -> None:
self._itf = interface
self.unit_addr = data[0]
self.function, self.register_addr = struct.unpack_from('>BH', data, 1)
if self.function in [Const.READ_COILS, Const.READ_DISCRETE_INPUTS]:
self.quantity = struct.unpack_from('>H', data, 4)[0]
if self.quantity < 0x0001 or self.quantity > 0x07D0:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
self.data = None
elif self.function in [Const.READ_HOLDING_REGISTERS, Const.READ_INPUT_REGISTER]:
self.quantity = struct.unpack_from('>H', data, 4)[0]
if self.quantity < 0x0001 or self.quantity > 0x007D:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
self.data = None
elif self.function == Const.WRITE_SINGLE_COIL:
self.quantity = None
self.data = data[4:6]
# allowed values: 0x0000 or 0xFF00
if (self.data[0] not in [0x00, 0xFF]) or self.data[1] != 0x00:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
elif self.function == Const.WRITE_SINGLE_REGISTER:
self.quantity = None
self.data = data[4:6]
# all values allowed
elif self.function == Const.WRITE_MULTIPLE_COILS:
self.quantity = struct.unpack_from('>H', data, 4)[0]
if self.quantity < 0x0001 or self.quantity > 0x07D0:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
self.data = data[7:]
if len(self.data) != ((self.quantity - 1) // 8) + 1:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
elif self.function == Const.WRITE_MULTIPLE_REGISTERS:
self.quantity = struct.unpack_from('>H', data, 4)[0]
if self.quantity < 0x0001 or self.quantity > 0x007B:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
self.data = data[7:]
if len(self.data) != self.quantity * 2:
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
else:
# Not implemented functions
self.quantity = None
self.data = data[4:]
def send_response(self,
values: Optional[list] = None,
signed: bool = True) -> None:
"""
Send a response via the configured interface.
:param values: The values
:type values: Optional[list]
:param signed: Indicates if signed values are used
:type signed: bool
"""
self._itf.send_response(self.unit_addr,
self.function,
self.register_addr,
self.quantity,
self.data,
values,
signed)
def send_exception(self, exception_code: int) -> None:
"""
Send an exception response.
:param exception_code: The exception code
:type exception_code: int
"""
self._itf.send_exception_response(self.unit_addr,
self.function,
exception_code)
class ModbusException(Exception):
"""Exception for signaling modbus errors"""
def __init__(self, function_code: int, exception_code: int) -> None:
self.function_code = function_code
self.exception_code = exception_code
class CommonModbusFunctions(object):
"""Common Modbus functions"""
def __init__(self):
pass
def read_coils(self,
slave_addr: int,
starting_addr: int,
coil_qty: int) -> List[bool]:
"""
Read coils (COILS).
:param slave_addr: The slave address
:type slave_addr: int
:param starting_addr: The coil starting address
:type starting_addr: int
:param coil_qty: The amount of coils to read
:type coil_qty: int
:returns: State of read coils as list
:rtype: List[bool]
"""
modbus_pdu = functions.read_coils(starting_address=starting_addr,
quantity=coil_qty)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=True)
status_pdu = functions.bytes_to_bool(byte_list=response,
bit_qty=coil_qty)
return status_pdu
def read_discrete_inputs(self,
slave_addr: int,
starting_addr: int,
input_qty: int) -> List[bool]:
"""
Read discrete inputs (ISTS).
:param slave_addr: The slave address
:type slave_addr: int
:param starting_addr: The discrete input starting address
:type starting_addr: int
:param input_qty: The amount of discrete inputs to read
:type input_qty: int
:returns: State of read discrete inputs as list
:rtype: List[bool]
"""
modbus_pdu = functions.read_discrete_inputs(
starting_address=starting_addr,
quantity=input_qty)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=True)
status_pdu = functions.bytes_to_bool(byte_list=response,
bit_qty=input_qty)
return status_pdu
def read_holding_registers(self,
slave_addr: int,
starting_addr: int,
register_qty: int,
signed: bool = True) -> Tuple[int, ...]:
"""
Read holding registers (HREGS).
:param slave_addr: The slave address
:type slave_addr: int
:param starting_addr: The holding register starting address
:type starting_addr: int
:param register_qty: The amount of holding registers to read
:type register_qty: int
:param signed: Indicates if signed
:type signed: bool
:returns: State of read holding register as tuple
:rtype: Tuple[int, ...]
"""
modbus_pdu = functions.read_holding_registers(
starting_address=starting_addr,
quantity=register_qty)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=True)
register_value = functions.to_short(byte_array=response, signed=signed)
return register_value
def read_input_registers(self,
slave_addr: int,
starting_addr: int,
register_qty: int,
signed: bool = True) -> Tuple[int, ...]:
"""
Read input registers (IREGS).
:param slave_addr: The slave address
:type slave_addr: int
:param starting_addr: The input register starting address
:type starting_addr: int
:param register_qty: The amount of input registers to read
:type register_qty: int
:param signed: Indicates if signed
:type signed: bool
:returns: State of read input register as tuple
:rtype: Tuple[int, ...]
"""
modbus_pdu = functions.read_input_registers(
starting_address=starting_addr,
quantity=register_qty)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=True)
register_value = functions.to_short(byte_array=response, signed=signed)
return register_value
def write_single_coil(self,
slave_addr: int,
output_address: int,
output_value: Union[int, bool]) -> bool:
"""
Update a single coil.
:param slave_addr: The slave address
:type slave_addr: int
:param output_address: The output address
:type output_address: int
:param output_value: The output value
:type output_value: Union[int, bool]
:returns: Result of operation
:rtype: bool
"""
modbus_pdu = functions.write_single_coil(output_address=output_address,
output_value=output_value)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=False)
if response is None:
return False
operation_status = functions.validate_resp_data(
data=response,
function_code=Const.WRITE_SINGLE_COIL,
address=output_address,
value=output_value,
signed=False)
return operation_status
def write_single_register(self,
slave_addr: int,
register_address: int,
register_value: int,
signed: bool = True) -> bool:
"""
Update a single register.
:param slave_addr: The slave address
:type slave_addr: int
:param register_address: The register address
:type register_address: int
:param register_value: The register value
:type register_value: int
:param signed: Indicates if signed
:type signed: bool
:returns: Result of operation
:rtype: bool
"""
modbus_pdu = functions.write_single_register(
register_address=register_address,
register_value=register_value,
signed=signed)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=False)
if response is None:
return False
operation_status = functions.validate_resp_data(
data=response,
function_code=Const.WRITE_SINGLE_REGISTER,
address=register_address,
value=register_value,
signed=signed)
return operation_status
def write_multiple_coils(self,
slave_addr: int,
starting_address: int,
output_values: List[Union[int, bool]]) -> bool:
"""
Update multiple coils.
:param slave_addr: The slave address
:type slave_addr: int
:param starting_address: The address of the first coil
:type starting_address: int
:param output_values: The output values
:type output_values: List[Union[int, bool]]
:returns: Result of operation
:rtype: bool
"""
modbus_pdu = functions.write_multiple_coils(
starting_address=starting_address,
value_list=output_values)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=False)
if response is None:
return False
operation_status = functions.validate_resp_data(
data=response,
function_code=Const.WRITE_MULTIPLE_COILS,
address=starting_address,
quantity=len(output_values))
return operation_status
def write_multiple_registers(self,
slave_addr: int,
starting_address: int,
register_values: List[int],
signed: bool = True) -> bool:
"""
Update multiple registers.
:param slave_addr: The slave address
:type slave_addr: int
:param starting_address: The starting address
:type starting_address: int
:param register_values: The register values
:type register_values: List[int]
:param signed: Indicates if signed
:type signed: bool
:returns: Result of operation
:rtype: bool
"""
modbus_pdu = functions.write_multiple_registers(
starting_address=starting_address,
register_values=register_values,
signed=signed)
response = self._send_receive(slave_addr=slave_addr,
modbus_pdu=modbus_pdu,
count=False)
if response is None:
return False
operation_status = functions.validate_resp_data(
data=response,
function_code=Const.WRITE_MULTIPLE_REGISTERS,
address=starting_address,
quantity=len(register_values),
signed=signed
)
return operation_status
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env python
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#
# Description summary taken from
# https://modbus.org/docs/Modbus_Application_Protocol_V1_1b3.pdf
from micropython import const
# function codes
# defined as const(), see https://github.com/micropython/micropython/issues/573
#: Read contiguous status of coils
READ_COILS = const(0x01) # COILS, [0, 1]
#: Read contiguous status of discrete inputs
READ_DISCRETE_INPUTS = const(0x02) # ISTS, [0, 1]
#: Read the contents of a contiguous block of holding registers
READ_HOLDING_REGISTERS = const(0x03) # HREGS, [0, 65535]
#: Read contiguous input registers
READ_INPUT_REGISTER = const(0x04) # IREGS, [0, 65535]
#: Write a single coil output status to ON or OFF
WRITE_SINGLE_COIL = const(0x05) # COILS, [0, 1]
#: Write a single holding register
WRITE_SINGLE_REGISTER = const(0x06) # HREGS, [0, 65535]
#: Force each coil in a sequence of coils to either ON or OFF
WRITE_MULTIPLE_COILS = const(0x0F) # COILS, [0, 1]
#: Write a block of contiguous registers
WRITE_MULTIPLE_REGISTERS = const(0x10) # HREGS, [0, 65535]
"""
Modify the contents of a specified holding register using a combination of an
AND mask, an OR mask, and the register's current contents
"""
MASK_WRITE_REGISTER = const(0x16)
"""
Perform a combination of one read operation and one write operation in a
single MODBUS transaction
"""
READ_WRITE_MULTIPLE_REGISTERS = const(0x17)
#: Read the contents of a First-In-First-Out (FIFO) queue of register
READ_FIFO_QUEUE = const(0x18)
#: Perform a file record read
READ_FILE_RECORD = const(0x14)
#: Perform a file record write
WRITE_FILE_RECORD = const(0x15)
#: Read the contents of eight Exception Status outputs
READ_EXCEPTION_STATUS = const(0x07)
#: Provide series of tests for checking the communication system (serial only)
DIAGNOSTICS = const(0x08)
#: Get status word and an event count from the remote device com event counter
GET_COM_EVENT_COUNTER = const(0x0B)
#: Get a status word, event count, message count, and a field of event bytes
GET_COM_EVENT_LOG = const(0x0C)
#: Read the description of the type, the current status, and other informations
REPORT_SERVER_ID = const(0x11)
#: Encapsulated Interface Transport
READ_DEVICE_IDENTIFICATION = const(0x2B)
# exception codes
#: Function code received in query is not an allowable action for the server
ILLEGAL_FUNCTION = const(0x01)
#: Data address received in query is not an allowable address for the server
ILLEGAL_DATA_ADDRESS = const(0x02)
#: A value contained in the query is not an allowable value for the server
ILLEGAL_DATA_VALUE = const(0x03)
"""
An unrecoverable error occurred while the server was attempting to perform the
requested action
"""
SERVER_DEVICE_FAILURE = const(0x04)
#: Response is returned to prevent a timeout error from occurring in the client
ACKNOWLEDGE = const(0x05)
#: Server is engaged in processing a long duration program command
SERVER_DEVICE_BUSY = const(0x06)
#: Server attempted to read record file, but detected a parity error in memory
MEMORY_PARITY_ERROR = const(0x08)
"""
Gateway was unable to allocate an internal communication path from the input
port to the output port for processing the request
"""
GATEWAY_PATH_UNAVAILABLE = const(0x0A)
#: No response was obtained from the target device
DEVICE_FAILED_TO_RESPOND = const(0x0B)
# Protocol Data Unit (PDU) constants
#: CRC length
CRC_LENGTH = const(0x02)
#: Error code offset
ERROR_BIAS = const(0x80)
#: High Data Response length
RESPONSE_HDR_LENGTH = const(0x02)
#: Error response length
ERROR_RESP_LEN = const(0x05)
#: Fixed response length
FIXED_RESP_LEN = const(0x08)
#: Modbus Application Protocol High Data Response length
MBAP_HDR_LENGTH = const(0x07)
#: CRC16 lookup table
CRC16_TABLE = (
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601,
0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01, 0x0CC0,
0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81,
0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941,
0x1B00, 0xDBC1, 0xDA81, 0x1A40, 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01,
0x1DC0, 0x1C80, 0xDC41, 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0,
0x1680, 0xD641, 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081,
0x1040, 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, 0x3C00,
0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, 0xFA01, 0x3AC0,
0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840, 0x2800, 0xE8C1, 0xE981,
0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, 0xEE01, 0x2EC0, 0x2F80, 0xEF41,
0x2D00, 0xEDC1, 0xEC81, 0x2C40, 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700,
0xE7C1, 0xE681, 0x2640, 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0,
0x2080, 0xE041, 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281,
0x6240, 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, 0xAA01,
0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840, 0x7800, 0xB8C1,
0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, 0xBE01, 0x7EC0, 0x7F80,
0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, 0xB401, 0x74C0, 0x7580, 0xB541,
0x7700, 0xB7C1, 0xB681, 0x7640, 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101,
0x71C0, 0x7080, 0xB041, 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0,
0x5280, 0x9241, 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481,
0x5440, 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, 0x8801,
0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, 0x4E00, 0x8EC1,
0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581,
0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 0x8201, 0x42C0, 0x4380, 0x8341,
0x4100, 0x81C1, 0x8081, 0x4040
)
# Code to generate the CRC-16 lookup table:
# def generate_crc16_table():
# crc_table = []
# for byte in range(256):
# crc = 0x0000
# for _ in range(8):
# if (byte ^ crc) & 0x0001:
# crc = (crc >> 1) ^ 0xa001
# else:
# crc >>= 1
# byte >>= 1
# crc_table.append(crc)
# return crc_table
+459
View File
@@ -0,0 +1,459 @@
#!/usr/bin/env python
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#
# system packages
import struct
# custom packages
from . import const as Const
# typing not natively supported on MicroPython
from .typing import List, Optional, Union
def read_coils(starting_address: int, quantity: int) -> bytes:
"""
Create Modbus Protocol Data Unit for reading coils.
:param starting_address: The starting address
:type starting_address: int
:param quantity: Quantity of coils
:type quantity: int
:returns: Packed Modbus message
:rtype: bytes
"""
if not (1 <= quantity <= 2000):
raise ValueError('Invalid number of coils')
return struct.pack('>BHH', Const.READ_COILS, starting_address, quantity)
def read_discrete_inputs(starting_address: int, quantity: int) -> bytes:
"""
Create Modbus Protocol Data Unit for reading discrete inputs.
:param starting_address: The starting address
:type starting_address: int
:param quantity: Quantity of coils
:type quantity: int
:returns: Packed Modbus message
:rtype: bytes
"""
if not (1 <= quantity <= 2000):
raise ValueError('Invalid number of discrete inputs')
return struct.pack('>BHH',
Const.READ_DISCRETE_INPUTS,
starting_address,
quantity)
def read_holding_registers(starting_address: int, quantity: int) -> bytes:
"""
Create Modbus Protocol Data Unit for reading holding registers.
:param starting_address: The starting address
:type starting_address: int
:param quantity: Quantity of coils
:type quantity: int
:returns: Packed Modbus message
:rtype: bytes
"""
if not (1 <= quantity <= 125):
raise ValueError('Invalid number of holding registers')
return struct.pack('>BHH',
Const.READ_HOLDING_REGISTERS,
starting_address,
quantity)
def read_input_registers(starting_address: int, quantity: int) -> bytes:
"""
Create Modbus Protocol Data Unit for reading input registers.
:param starting_address: The starting address
:type starting_address: int
:param quantity: Quantity of coils
:type quantity: int
:returns: Packed Modbus message
:rtype: bytes
"""
if not (1 <= quantity <= 125):
raise ValueError('Invalid number of input registers')
return struct.pack('>BHH',
Const.READ_INPUT_REGISTER,
starting_address,
quantity)
def write_single_coil(output_address: int,
output_value: Union[int, bool]) -> bytes:
"""
Create Modbus message to update single coil
:param output_address: The output address
:type output_address: int
:param output_value: The output value
:type output_value: Union[int, bool]
:returns: Packed Modbus message
:rtype: bytes
"""
if output_value not in [0x0000, 0xFF00, False, True, 0, 1]:
raise ValueError('Illegal coil value')
if output_value not in [0x0000, 0xFF00]:
if output_value:
output_value = 0xFF00
else:
output_value = 0x0000
return struct.pack('>BHH',
Const.WRITE_SINGLE_COIL,
output_address,
output_value)
def write_single_register(register_address: int,
register_value: int,
signed: bool = True) -> bytes:
"""
Create Modbus message to writes a single register
:param register_address: The register address
:type register_address: int
:param register_value: The register value
:type register_value: int
:param signed: Flag whether data is signed or not
:type signed: bool
:returns: Packed Modbus message
:rtype: bytes
"""
fmt = 'h' if signed else 'H'
return struct.pack('>BH' + fmt,
Const.WRITE_SINGLE_REGISTER,
register_address,
register_value)
def write_multiple_coils(starting_address: int,
value_list: List[Union[int, bool]]) -> bytes:
"""
Create Modbus message to update multiple coils
:param starting_address: The starting address
:type starting_address: int
:param value_list: The list of output values
:type value_list: List[Union[int, bool]]
:returns: Packed Modbus message
:rtype: bytes
"""
if not (1 <= len(value_list) <= 0x07B0):
raise ValueError('Invalid quantity of outputs')
sectioned_list = [value_list[i:i + 8] for i in range(0, len(value_list), 8)] # noqa: E501
output_value = []
for index, byte in enumerate(sectioned_list):
# see https://github.com/brainelectronics/micropython-modbus/issues/22
# output = sum(v << i for i, v in enumerate(byte))
output = 0
for bit in byte:
output = (output << 1) | bit
output_value.append(output)
fmt = 'B' * len(output_value)
quantity = len(value_list)
byte_count = quantity // 8
if quantity % 8:
byte_count += 1
return struct.pack('>BHHB' + fmt,
Const.WRITE_MULTIPLE_COILS,
starting_address,
quantity,
byte_count,
*output_value)
def write_multiple_registers(starting_address: int,
register_values: List[int],
signed: bool = True) -> bytes:
"""
Create Modbus message to update multiple coils
:param starting_address: The starting address
:type starting_address: int
:param register_values: The list of output value
:type register_values: List[int, bool]
:param signed: Flag whether data is signed or not
:type signed: bool
:returns: Packed Modbus message
:rtype: bytes
"""
if not (1 <= len(register_values) <= 123):
raise ValueError('Invalid number of registers')
quantity = len(register_values)
byte_count = quantity * 2
fmt = ('h' if signed else 'H') * quantity
return struct.pack('>BHHB' + fmt,
Const.WRITE_MULTIPLE_REGISTERS,
starting_address,
quantity,
byte_count,
*register_values)
def validate_resp_data(data: bytes,
function_code: int,
address: int,
value: int = None,
quantity: int = None,
signed: bool = True) -> bool:
"""
Validate the response data.
:param data: The data
:type data: bytes
:param function_code: The function code
:type function_code: int
:param address: The address
:type address: int
:param value: The value
:type value: int
:param quantity: The quantity
:type quantity: int
:param signed: Indicates if signed
:type signed: bool
:returns: True if valid, False otherwise
:rtype: bool
"""
fmt = '>H' + ('h' if signed else 'H')
if function_code in [Const.WRITE_SINGLE_COIL, Const.WRITE_SINGLE_REGISTER]:
resp_addr, resp_value = struct.unpack(fmt, data)
# if bool(True) or int(1) is used as "output_value" of
# "write_single_coil" it will be internally converted to int(0xFF00),
# see Modbus specification, which is actually int(65280).
# Due to the non binary, but real value comparison of "value" and
# "resp_value", it would never match without the next two lines
# see #21
if function_code == Const.WRITE_SINGLE_COIL:
resp_value = bool(resp_value)
value = bool(value)
if (address == resp_addr) and (value == resp_value):
return True
elif function_code in [Const.WRITE_MULTIPLE_COILS,
Const.WRITE_MULTIPLE_REGISTERS]:
resp_addr, resp_qty = struct.unpack(fmt, data)
if (address == resp_addr) and (quantity == resp_qty):
return True
return False
def response(function_code: int,
request_register_addr: int,
request_register_qty: int,
request_data: list,
value_list: Optional[list] = None,
signed: bool = True) -> bytes:
"""
Construct a Modbus response Protocol Data Unit
:param function_code: The function code
:type function_code: int
:param request_register_addr: The request register address
:type request_register_addr: int
:param request_register_qty: The request register qty
:type request_register_qty: int
:param request_data: The request data
:type request_data: list
:param value_list: The values
:type value_list: Optional[list]
:param signed: Indicates if signed
:type signed: bool
:returns: Protocol data unit
:rtype: bytes
"""
if function_code in [Const.READ_COILS, Const.READ_DISCRETE_INPUTS]:
sectioned_list = [value_list[i:i + 8] for i in range(0, len(value_list), 8)] # noqa: E501
output_value = []
for index, byte in enumerate(sectioned_list):
output = 0
for i, bit in enumerate(byte):
output |= bit << i
output_value.append(output)
fmt = 'B' * len(output_value)
return struct.pack('>BB' + fmt,
function_code,
((len(value_list) - 1) // 8) + 1,
*output_value)
elif function_code in [Const.READ_HOLDING_REGISTERS,
Const.READ_INPUT_REGISTER]:
quantity = len(value_list)
if not (0x0001 <= quantity <= 0x007D):
raise ValueError('invalid number of registers')
if signed is True or signed is False:
fmt = ('h' if signed else 'H') * quantity
else:
fmt = ''
for s in signed:
fmt += 'h' if s else 'H'
return struct.pack('>BB' + fmt,
function_code,
quantity * 2,
*value_list)
elif function_code in [Const.WRITE_SINGLE_COIL,
Const.WRITE_SINGLE_REGISTER]:
return struct.pack('>BHBB',
function_code,
request_register_addr,
*request_data)
elif function_code in [Const.WRITE_MULTIPLE_COILS,
Const.WRITE_MULTIPLE_REGISTERS]:
return struct.pack('>BHH',
function_code,
request_register_addr,
request_register_qty)
def exception_response(function_code: int, exception_code: int) -> bytes:
"""
Create Modbus exception response
:param function_code: The function code
:type function_code: int
:param exception_code: The exception code
:type exception_code: int
:returns: Packed Modbus message
:rtype: bytes
"""
return struct.pack('>BB', Const.ERROR_BIAS + function_code, exception_code)
def bytes_to_bool(byte_list: bytes, bit_qty: Optional[int] = 1) -> List[bool]:
"""
Convert bytes to list of boolean values
:param byte_list: The byte list
:type byte_list: bytes
:param bit_qty: Amount of bits received
:type bit_qty: Optional[int]
:returns: Boolean representation
:rtype: List[bool]
"""
bool_list = []
for index, byte in enumerate(byte_list):
this_qty = bit_qty
if this_qty >= 8:
this_qty = 8
# evil hack for missing keyword support in MicroPython format()
fmt = '{:0' + str(this_qty) + 'b}'
binary_str = fmt.format(byte)
bool_list.extend([bool(int(binary_str[i])) for i in range(len(binary_str)-1, -1, -1)])
bit_qty -= 8
return bool_list
def to_short(byte_array: bytes, signed: bool = True) -> bytes:
"""
Convert bytes to tuple of integer values
:param byte_array: The byte array
:type byte_array: bytes
:param signed: Indicates if signed
:type signed: bool
:returns: Integer representation
:rtype: bytes
"""
response_quantity = int(len(byte_array) / 2)
fmt = '>' + (('h' if signed else 'H') * response_quantity)
return struct.unpack(fmt, byte_array)
def float_to_bin(num: float) -> bin:
"""
Convert floating point value to binary
See IEEE 754
:param num: The number
:type num: float
:returns: Binary representation
:rtype: bin
"""
# no "zfill" available in MicroPython
# return bin(struct.unpack('!I', struct.pack('!f', num))[0])[2:].zfill(32)
return '{:0>{w}}'.format(
bin(struct.unpack('!I', struct.pack('!f', num))[0])[2:],
w=32)
def bin_to_float(binary: str) -> float:
"""
Convert binary string to floating point value
:param binary: The binary string
:type binary: str
:returns: Converted floating point value
:rtype: float
"""
return struct.unpack('!f', struct.pack('!I', int(binary, 2)))[0]
def int_to_bin(num: int) -> str:
"""
Convert integer to binary
:param num: The number
:type num: int
:returns: Binary representation of given input
:rtype: str
"""
return "{0:b}".format(num)
+873
View File
@@ -0,0 +1,873 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Modbus register abstraction class
Used to add, remove, set and get values or states of a register or coil.
Additional helper properties and functions like getters for changed registers
are available as well.
This class is inherited by the Modbus client implementations
:py:class:`umodbus.serial.ModbusRTU` and :py:class:`umodbus.tcp.ModbusTCP`
"""
# system packages
import time
# custom packages
from . import functions
from . import const as Const
from .common import Request
# typing not natively supported on MicroPython
from .typing import Callable, dict_keys, List, Optional, Union
class Modbus(object):
"""
Modbus register abstraction
:param itf: Abstraction interface
:type itf: Callable
:param addr_list: List of addresses
:type addr_list: List[int]
"""
def __init__(self, itf, addr_list: List[int]) -> None:
self._itf = itf
self._addr_list = addr_list
# modbus register types with their default value
self._available_register_types = ['COILS', 'HREGS', 'IREGS', 'ISTS']
self._register_dict = dict()
for reg_type in self._available_register_types:
self._register_dict[reg_type] = dict()
self._default_vals = dict(zip(self._available_register_types,
[False, 0, 0, False]))
# registers which can be set by remote device
self._changeable_register_types = ['COILS', 'HREGS']
self._changed_registers = dict()
for reg_type in self._changeable_register_types:
self._changed_registers[reg_type] = dict()
def process(self) -> bool:
"""
Process the Modbus requests.
:returns: Result of processing, True on success, False otherwise
:rtype: bool
"""
reg_type = None
req_type = None
request = self._itf.get_request(unit_addr_list=self._addr_list,
timeout=0)
if request is None:
return False
if request.function == Const.READ_COILS:
# Coils (setter+getter) [0, 1]
# function 01 - read single register
reg_type = 'COILS'
req_type = 'READ'
elif request.function == Const.READ_DISCRETE_INPUTS:
# Ists (only getter) [0, 1]
# function 02 - read input status (discrete inputs/digital input)
reg_type = 'ISTS'
req_type = 'READ'
elif request.function == Const.READ_HOLDING_REGISTERS:
# Hregs (setter+getter) [0, 65535]
# function 03 - read holding register
reg_type = 'HREGS'
req_type = 'READ'
elif request.function == Const.READ_INPUT_REGISTER:
# Iregs (only getter) [0, 65535]
# function 04 - read input registers
reg_type = 'IREGS'
req_type = 'READ'
elif (request.function == Const.WRITE_SINGLE_COIL or
request.function == Const.WRITE_MULTIPLE_COILS):
# Coils (setter+getter) [0, 1]
# function 05 - write single coil
# function 15 - write multiple coil
reg_type = 'COILS'
req_type = 'WRITE'
elif (request.function == Const.WRITE_SINGLE_REGISTER or
request.function == Const.WRITE_MULTIPLE_REGISTERS):
# Hregs (setter+getter) [0, 65535]
# function 06 - write holding register
# function 16 - write multiple holding register
reg_type = 'HREGS'
req_type = 'WRITE'
else:
request.send_exception(Const.ILLEGAL_FUNCTION)
if reg_type:
if req_type == 'READ':
self._process_read_access(request=request, reg_type=reg_type)
elif req_type == 'WRITE':
self._process_write_access(request=request, reg_type=reg_type)
return True
def _create_response(self,
request: Request,
reg_type: str) -> Union[List[bool], List[int]]:
"""
Create a response.
:param request: The request
:type request: Request
:param reg_type: The register type
:type reg_type: str
:returns: Values of this register
:rtype: Union[List[bool], List[int]]
"""
data = []
default_value = {'val': 0}
reg_dict = self._register_dict[reg_type]
if reg_type in ['COILS', 'ISTS']:
default_value = {'val': False}
for addr in range(request.register_addr,
request.register_addr + request.quantity):
value = reg_dict.get(addr, default_value)['val']
if isinstance(value, (list, tuple)):
data.extend(value)
else:
data.append(value)
# caution LSB vs MSB
# [
# 1, 0, 1, 1, 0, 0, 1, 1, # 0xB3
# 1, 1, 0, 1, 0, 1, 1, 0, # 0xD6
# 1, 0, 1 # 0x5
# ]
# but should be, documented at #38, see
# https://github.com/brainelectronics/micropython-modbus/issues/38
# this is only an issue of data provisioning as client/slave,
# it has thereby NOT to be fixed in
# :py:function:`umodbus.functions.bytes_to_bool`
# [
# 1, 1, 0, 0, 1, 1, 0, 1, # 0xCD
# 0, 1, 1, 0, 1, 0, 1, 1, # 0x6B
# 1, 0, 1 # 0x5
# ]
# 27 .... 20
# CD 1100 1101
#
# 35 .... 28
# 6B 0110 1011
#
# 43 .... 36
# 05 0000 0101
#
# 1011 0011 1101 0110 1010 0000
return data
def _process_read_access(self, request: Request, reg_type: str) -> None:
"""
Process read access to register
:param request: The request
:type request: Request
:param reg_type: The register type
:type reg_type: str
"""
address = request.register_addr
if address in self._register_dict[reg_type]:
if self._register_dict[reg_type][address].get('on_get_cb', 0):
vals = self._create_response(request=request,
reg_type=reg_type)
_cb = self._register_dict[reg_type][address]['on_get_cb']
_cb(reg_type=reg_type, address=address, val=vals)
vals = self._create_response(request=request, reg_type=reg_type)
request.send_response(vals)
else:
request.send_exception(Const.ILLEGAL_DATA_ADDRESS)
def _process_write_access(self, request: Request, reg_type: str) -> None:
"""
Process write access to register
:param request: The request
:type request: Request
:param reg_type: The register type
:type reg_type: str
"""
address = request.register_addr
val = 0
valid_register = False
if address in self._register_dict[reg_type]:
if request.data is None:
request.send_exception(Const.ILLEGAL_DATA_VALUE)
return
if reg_type == 'COILS':
valid_register = True
if request.function == Const.WRITE_SINGLE_COIL:
val = request.data[0]
if 0x00 < val < 0xFF:
valid_register = False
request.send_exception(Const.ILLEGAL_DATA_VALUE)
else:
val = [(val == 0xFF)]
elif request.function == Const.WRITE_MULTIPLE_COILS:
tmp = int.from_bytes(request.data, "big")
val = [
bool(tmp & (1 << n)) for n in range(request.quantity)
]
if valid_register:
self.set_coil(address=address, value=val)
elif reg_type == 'HREGS':
valid_register = True
val = list(functions.to_short(byte_array=request.data,
signed=False))
if request.function in [Const.WRITE_SINGLE_REGISTER,
Const.WRITE_MULTIPLE_REGISTERS]:
self.set_hreg(address=address, value=val)
else:
# nothing except holding registers or coils can be set
request.send_exception(Const.ILLEGAL_FUNCTION)
if valid_register:
request.send_response()
self._set_changed_register(reg_type=reg_type,
address=address,
value=val)
if self._register_dict[reg_type][address].get('on_set_cb', 0):
_cb = self._register_dict[reg_type][address]['on_set_cb']
_cb(reg_type=reg_type, address=address, val=val)
else:
request.send_exception(Const.ILLEGAL_DATA_ADDRESS)
def add_coil(self,
address: int,
value: Union[bool, List[bool]] = False,
on_set_cb: Callable[[str, int, Union[List[bool], List[int]]],
None] = None,
on_get_cb: Callable[[str, int, Union[List[bool], List[int]]],
None] = None) -> None:
"""
Add a coil to the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: Union[bool, List[bool]], optional
:param on_set_cb: Callback on setting the coil
:type on_set_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
:param on_get_cb: Callback on getting the coil
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
"""
self._set_reg_in_dict(reg_type='COILS',
address=address,
value=value,
on_set_cb=on_set_cb,
on_get_cb=on_get_cb)
def remove_coil(self, address: int) -> Union[None, bool, List[bool]]:
"""
Remove a coil from the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:returns: Register value, None if register did not exist in dict
:rtype: Union[None, bool, List[bool]]
"""
return self._remove_reg_from_dict(reg_type='COILS', address=address)
def set_coil(self,
address: int,
value: Union[bool, List[bool]] = False) -> None:
"""
Set the coil value.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: Union[bool, List[bool]], optional
"""
self._set_reg_in_dict(reg_type='COILS',
address=address,
value=value)
def get_coil(self, address: int) -> Union[bool, List[bool]]:
"""
Get the coil value.
:param address: The address (ID) of the register
:type address: bool
:returns: Coil value
:rtype: Union[bool, List[bool]]
"""
return self._get_reg_in_dict(reg_type='COILS',
address=address)
@property
def coils(self) -> dict_keys:
"""
Get the configured coils.
:returns: The dictionary keys.
:rtype: dict_keys
"""
return self._get_regs_of_dict(reg_type='COILS')
def add_hreg(self,
address: int,
value: Union[int, List[int]] = 0,
on_set_cb: Callable[[str, int, List[int]], None] = None,
on_get_cb: Callable[[str, int, List[int]], None] = None) -> None:
"""
Add a holding register to the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: Union[int, List[int]], optional
:param on_set_cb: Callback on setting the holding register
:type on_set_cb: Callable[[str, int, List[int]], None]
:param on_get_cb: Callback on getting the holding register
:type on_get_cb: Callable[[str, int, List[int]], None]
"""
self._set_reg_in_dict(reg_type='HREGS',
address=address,
value=value,
on_set_cb=on_set_cb,
on_get_cb=on_get_cb)
def remove_hreg(self, address: int) -> Union[None, int, List[int]]:
"""
Remove a holding register from the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:returns: Register value, None if register did not exist in dict
:rtype: Union[None, int, List[int]]
"""
return self._remove_reg_from_dict(reg_type='HREGS', address=address)
def set_hreg(self, address: int, value: Union[int, List[int]] = 0) -> None:
"""
Set the holding register value.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: int or list of int, optional
"""
self._set_reg_in_dict(reg_type='HREGS',
address=address,
value=value)
def get_hreg(self, address: int) -> Union[int, List[int]]:
"""
Get the holding register value.
:param address: The address (ID) of the register
:type address: int
:returns: Holding register value
:rtype: Union[int, List[int]]
"""
return self._get_reg_in_dict(reg_type='HREGS',
address=address)
@property
def hregs(self) -> dict_keys:
"""
Get the configured holding registers.
:returns: The dictionary keys.
:rtype: dict_keys
"""
return self._get_regs_of_dict(reg_type='HREGS')
def add_ist(self,
address: int,
value: Union[bool, List[bool]] = False,
on_get_cb: Callable[[str, int, Union[List[bool], List[int]]],
None] = None) -> None:
"""
Add a discrete input register to the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: bool or list of bool, optional
:param on_get_cb: Callback on getting the discrete input register
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
"""
self._set_reg_in_dict(reg_type='ISTS',
address=address,
value=value,
on_get_cb=on_get_cb)
def remove_ist(self, address: int) -> Union[None, bool, List[bool]]:
"""
Remove a discrete input register from the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:returns: Register value, None if register did not exist in dict
:rtype: Union[None, bool, List[bool]]
"""
return self._remove_reg_from_dict(reg_type='ISTS', address=address)
def set_ist(self, address: int, value: bool = False) -> None:
"""
Set the discrete input register value.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: bool or list of bool, optional
"""
self._set_reg_in_dict(reg_type='ISTS',
address=address,
value=value)
def get_ist(self, address: int) -> Union[bool, List[bool]]:
"""
Get the discrete input register value.
:param address: The address (ID) of the register
:type address: int
:returns: Discrete input register value
:rtype: Union[bool, List[bool]]
"""
return self._get_reg_in_dict(reg_type='ISTS',
address=address)
@property
def ists(self) -> dict_keys:
"""
Get the configured discrete input registers.
:returns: The dictionary keys.
:rtype: dict_keys
"""
return self._get_regs_of_dict(reg_type='ISTS')
def add_ireg(self,
address: int,
value: Union[int, List[int]] = 0,
on_get_cb: Callable[[str, int, Union[List[bool], List[int]]],
None] = None) -> None:
"""
Add an input register to the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: Union[int, List[int]], optional
:param on_get_cb: Callback on getting the input register
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
"""
self._set_reg_in_dict(reg_type='IREGS',
address=address,
value=value,
on_get_cb=on_get_cb)
def remove_ireg(self, address: int) -> Union[None, int, List[int]]:
"""
Remove an input register from the modbus register dictionary.
:param address: The address (ID) of the register
:type address: int
:returns: Register value, None if register did not exist in dict
:rtype: Union[None, int, List[int]]
"""
return self._remove_reg_from_dict(reg_type='IREGS', address=address)
def set_ireg(self, address: int, value: Union[int, List[int]] = 0) -> None:
"""
Set the input register value.
:param address: The address (ID) of the register
:type address: int
:param value: The default value
:type value: Union[int, List[int]], optional
"""
self._set_reg_in_dict(reg_type='IREGS',
address=address,
value=value)
def get_ireg(self, address: int) -> Union[int, List[int]]:
"""
Get the input register value.
:param address: The address (ID) of the register
:type address: int
:returns: Input register value
:rtype: Union[int, List[int]]
"""
return self._get_reg_in_dict(reg_type='IREGS',
address=address)
@property
def iregs(self) -> dict_keys:
"""
Get the configured input registers.
:returns: The dictionary keys.
:rtype: dict_keys
"""
return self._get_regs_of_dict(reg_type='IREGS')
def _set_reg_in_dict(self,
reg_type: str,
address: int,
value: Union[bool, int, List[bool], List[int]],
on_set_cb: Callable[[str, int, Union[List[bool],
List[int]]],
None] = None,
on_get_cb: Callable[[str, int, Union[List[bool],
List[int]]],
None] = None) -> None:
"""
Set the register value in the dictionary of registers.
:param reg_type: The register type
:type reg_type: str
:param address: The address (ID) of the register
:type address: int
:param value: The value(s) of the register(s)
:type value: Union[bool, int, List[bool], List[int]]
:param on_set_cb: Callback on setting the register
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
:param on_get_cb: Callback on getting the register
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
:raise KeyError: No register at specified address found
"""
if not self._check_valid_register(reg_type=reg_type):
raise KeyError('{} is not a valid register type of {}'.
format(reg_type, self._available_register_types))
if isinstance(value, (list, tuple)):
# flatten the list and add single registers only
for idx, val in enumerate(value):
this_addr = address + idx
self._set_single_reg_in_dict(reg_type=reg_type,
address=this_addr,
value=val,
on_set_cb=on_set_cb,
on_get_cb=on_get_cb)
else:
self._set_single_reg_in_dict(reg_type=reg_type,
address=address,
value=value,
on_set_cb=on_set_cb,
on_get_cb=on_get_cb)
def _set_single_reg_in_dict(self,
reg_type: str,
address: int,
value: Union[bool, int],
on_set_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
] = None,
on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
] = None) -> None:
"""
Set a register value in the dictionary of registers.
:param reg_type: The register type
:type reg_type: str
:param address: The address (ID) of the register
:type address: int
:param value: The value of the register
:type value: Union[bool, int]
:param on_set_cb: Callback on setting the register
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
:param on_get_cb: Callback on getting the register
:type on_get_cb: Callable[
[str, int, Union[List[bool], List[int]]],
None
]
"""
data = {'val': value}
# if the register exists already in the register dict a "set_*"
# function might have called this functions
if address in self._register_dict[reg_type]:
# try to get the (already) registered callback function from the
# register dict of this address with the this time call function
# parameter callback value as fallback
on_set_cb = self._register_dict[reg_type][address].get('on_set_cb',
on_set_cb)
on_get_cb = self._register_dict[reg_type][address].get('on_get_cb',
on_get_cb)
if callable(on_set_cb):
data['on_set_cb'] = on_set_cb
if callable(on_get_cb):
data['on_get_cb'] = on_get_cb
self._register_dict[reg_type][address] = data
def _remove_reg_from_dict(self,
reg_type: str,
address: int) -> Union[None, bool, int, List[bool], List[int]]:
"""
Remove the register from the dictionary of registers.
:param reg_type: The register type
:type reg_type: str
:param address: The address (ID) of the register
:type address: int
:raise KeyError: No register at specified address found
:returns: Register value, None if register did not exist in dict
:rtype: Union[None, bool, int, List[bool], List[int]]
"""
if not self._check_valid_register(reg_type=reg_type):
raise KeyError('{} is not a valid register type of {}'.
format(reg_type, self._available_register_types))
return self._register_dict[reg_type].pop(address, None)
def _get_reg_in_dict(self,
reg_type: str,
address: int) -> Union[bool, int, List[bool], List[int]]:
"""
Get the register value from the dictionary of registers.
:param reg_type: The register type
:type reg_type: str
:param address: The address (ID) of the register
:type address: int
:raise KeyError: No register at specified address found
:returns: Register value
:rtype: Union[bool, int, List[bool], List[int]]
"""
if not self._check_valid_register(reg_type=reg_type):
raise KeyError('{} is not a valid register type of {}'.
format(reg_type, self._available_register_types))
if address in self._register_dict[reg_type]:
return self._register_dict[reg_type][address]['val']
else:
raise KeyError('No {} available for the register address {}'.
format(reg_type, address))
def _get_regs_of_dict(self, reg_type: str) -> dict_keys:
"""
Get all configured registers of specified register type.
:param reg_type: The register type
:type reg_type: str
:raise KeyError: No register at specified address found
:returns: The configured registers of the specified register type.
:rtype: dict_keys
"""
if not self._check_valid_register(reg_type=reg_type):
raise KeyError('{} is not a valid register type of {}'.
format(reg_type, self._available_register_types))
return self._register_dict[reg_type].keys()
def _check_valid_register(self, reg_type: str) -> bool:
"""
Check register type to be a valid modbus register
:param reg_type: The register type
:type reg_type: str
:returns: Flag whether register type is valid
:rtype: bool
"""
if reg_type in self._available_register_types:
return True
else:
return False
@property
def changed_registers(self) -> dict:
"""
Get the changed registers.
:returns: The changed registers.
:rtype: dict
"""
return self._changed_registers
@property
def changed_coils(self) -> dict:
"""
Get the changed coil registers.
:returns: The changed coil registers.
:rtype: dict
"""
return self._changed_registers['COILS']
@property
def changed_hregs(self) -> dict:
"""
Get the changed holding registers.
:returns: The changed holding registers.
:rtype: dict
"""
return self._changed_registers['HREGS']
def _set_changed_register(self,
reg_type: str,
address: int,
value: Union[bool, int, List[bool], List[int]]) -> None:
"""
Set the register value in the dictionary of changed registers.
:param reg_type: The register type
:type reg_type: str
:param address: The address (ID) of the register
:type address: int
:param value: The value
:type value: Union[bool, int, List[bool], List[int]]
:raise KeyError: Register can not be changed externally
"""
if reg_type in self._changeable_register_types:
if isinstance(value, (list, tuple)):
for idx, val in enumerate(value):
content = {'val': val, 'time': time.ticks_ms()}
self._changed_registers[reg_type][address + idx] = content
else:
content = {'val': value, 'time': time.ticks_ms()}
self._changed_registers[reg_type][address] = content
else:
raise KeyError('{} can not be changed externally'.format(reg_type))
def _remove_changed_register(self,
reg_type: str,
address: int,
timestamp: int) -> bool:
"""
Remove the register from the dictionary of changed registers.
:param reg_type: The register type
:type reg_type: str
:param address: The address (ID) of the register
:type address: int
:param timestamp: The timestamp of the change in milliseconds
:type timestamp: int
:raise KeyError: No register at specified address found
:returns: Result of removing register from dict
:rtype: bool
"""
result = False
if reg_type in self._changeable_register_types:
_changed_register_timestamp = self._changed_registers[reg_type][address]['time']
if _changed_register_timestamp == timestamp:
self._changed_registers[reg_type].pop(address, None)
result = True
else:
raise KeyError('{} is not a valid register type of {}'.
format(reg_type, self._changeable_register_types))
return result
def setup_registers(self,
registers: dict = dict(),
use_default_vals: Optional[bool] = False) -> None:
"""
Setup all registers of the client
:param registers: The registers
:type registers: dict
:param use_default_vals: Flag to use dummy default values
:type use_default_vals: Optional[bool]
"""
if len(registers):
for reg_type, default_val in self._default_vals.items():
if reg_type in registers:
for reg, val in registers[reg_type].items():
address = val['register']
if use_default_vals:
if 'len' in val:
value = [default_val] * val['len']
else:
value = default_val
else:
value = val['val']
on_set_cb = val.get('on_set_cb', None)
on_get_cb = val.get('on_get_cb', None)
if reg_type == 'COILS':
self.add_coil(address=address,
value=value,
on_set_cb=on_set_cb,
on_get_cb=on_get_cb)
elif reg_type == 'HREGS':
self.add_hreg(address=address,
value=value,
on_set_cb=on_set_cb,
on_get_cb=on_get_cb)
elif reg_type == 'ISTS':
self.add_ist(address=address,
value=value,
on_get_cb=on_get_cb) # only getter
elif reg_type == 'IREGS':
self.add_ireg(address=address,
value=value,
on_get_cb=on_get_cb) # only getter
else:
# invalid register type
pass
else:
pass
+476
View File
@@ -0,0 +1,476 @@
#!/usr/bin/env python
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#
# system packages
from machine import UART
from machine import Pin
import struct
import time
# custom packages
from . import const as Const
from . import functions
from .common import Request, CommonModbusFunctions
from .common import ModbusException
from .modbus import Modbus
# typing not natively supported on MicroPython
from .typing import List, Optional, Union
class ModbusRTU(Modbus):
"""
Modbus RTU client class
:param addr: The address of this device on the bus
:type addr: int
:param baudrate: The baudrate, default 9600
:type baudrate: int
:param data_bits: The data bits, default 8
:type data_bits: int
:param stop_bits: The stop bits, default 1
:type stop_bits: int
:param parity: The parity, default None
:type parity: Optional[int]
:param pins: The pins as list [TX, RX]
:type pins: List[Union[int, Pin], Union[int, Pin]]
:param ctrl_pin: The control pin
:type ctrl_pin: int
:param uart_id: The ID of the used UART
:type uart_id: int
"""
def __init__(self,
addr: int,
baudrate: int = 9600,
data_bits: int = 8,
stop_bits: int = 1,
parity: Optional[int] = None,
pins: List[Union[int, Pin], Union[int, Pin]] = None,
ctrl_pin: int = None,
uart_id: int = 1):
super().__init__(
# set itf to Serial object, addr_list to [addr]
Serial(uart_id=uart_id,
baudrate=baudrate,
data_bits=data_bits,
stop_bits=stop_bits,
parity=parity,
pins=pins,
ctrl_pin=ctrl_pin),
[addr]
)
class Serial(CommonModbusFunctions):
def __init__(self,
uart_id: int = 1,
baudrate: int = 9600,
data_bits: int = 8,
stop_bits: int = 1,
parity=None,
pins: List[Union[int, Pin], Union[int, Pin]] = None,
ctrl_pin: int = None):
"""
Setup Serial/RTU Modbus
:param uart_id: The ID of the used UART
:type uart_id: int
:param baudrate: The baudrate, default 9600
:type baudrate: int
:param data_bits: The data bits, default 8
:type data_bits: int
:param stop_bits: The stop bits, default 1
:type stop_bits: int
:param parity: The parity, default None
:type parity: Optional[int]
:param pins: The pins as list [TX, RX]
:type pins: List[Union[int, Pin], Union[int, Pin]]
:param ctrl_pin: The control pin
:type ctrl_pin: int
"""
# UART flush function is introduced in Micropython v1.20.0
self._has_uart_flush = callable(getattr(UART, "flush", None))
if ctrl_pin is not None and ctrl_pin < 0:
self._uart = UART(uart_id,
baudrate=baudrate,
bits=data_bits,
parity=parity,
stop=stop_bits,
# timeout_chars=2, # WiPy only
pins=pins, # WiPy only
flow=-ctrl_pin
)
ctrl_pin = None
else:
self._uart = UART(uart_id,
baudrate=baudrate,
bits=data_bits,
parity=parity,
stop=stop_bits,
# timeout_chars=2, # WiPy only
pins=pins # WiPy only
)
if ctrl_pin is not None:
self._ctrlPin = Pin(ctrl_pin, mode=Pin.OUT)
else:
self._ctrlPin = None
# timing of 1 character in microseconds (us)
self._t1char = (1000000 * (data_bits + stop_bits + 2)) // baudrate
# inter-frame delay in microseconds (us)
# - <= 19200 bps: 3.5x timing of 1 character
# - > 19200 bps: 1750 us
if baudrate <= 19200:
self._inter_frame_delay = (self._t1char * 3500) // 1000
else:
self._inter_frame_delay = 1750
def _calculate_crc16(self, data: bytearray) -> bytes:
"""
Calculates the CRC16.
:param data: The data
:type data: bytearray
:returns: The crc 16.
:rtype: bytes
"""
crc = 0xFFFF
for char in data:
crc = (crc >> 8) ^ Const.CRC16_TABLE[((crc) ^ char) & 0xFF]
return struct.pack('<H', crc)
def _exit_read(self, response: bytearray) -> bool:
"""
Return on modbus read error
:param response: The response
:type response: bytearray
:returns: State of basic read response evaluation,
True if entire response has been read
:rtype: bool
"""
response_len = len(response)
if response_len >= 2 and response[1] >= Const.ERROR_BIAS:
if response_len < Const.ERROR_RESP_LEN:
return False
elif response_len >= 3 and (Const.READ_COILS <= response[1] <= Const.READ_INPUT_REGISTER):
expected_len = Const.RESPONSE_HDR_LENGTH + 1 + response[2] + Const.CRC_LENGTH
if response_len < expected_len:
return False
elif response_len < Const.FIXED_RESP_LEN:
return False
return True
def _uart_read(self) -> bytearray:
"""
Read incoming slave response from UART
:returns: Read content
:rtype: bytearray
"""
response = bytearray()
# TODO: use some kind of hint or user-configurable delay
# to determine this loop counter
for x in range(1, 120):
rx = self._uart.read()
if rx is not None:
# WiPy only
# response.extend(self._uart.readall())
response.extend(rx)
# variable length function codes may require multiple reads
if self._exit_read(response):
break
# wait for the maximum time between two frames
time.sleep_us(self._inter_frame_delay)
return response
def _uart_read_frame(self, timeout: Optional[int] = None) -> bytearray:
"""
Read a Modbus frame
:param timeout: The timeout
:type timeout: Optional[int]
:returns: Received message
:rtype: bytearray
"""
received_bytes = bytearray()
if self._uart.any() <= 0:
return received_bytes
# set default timeout to at twice the inter-frame delay
if timeout == 0 or timeout is None:
timeout = 2 * self._inter_frame_delay # in microseconds
start_us = time.ticks_us()
#print(start_us)
# stay inside this while loop at least for the timeout time
while (time.ticks_diff(time.ticks_us(), start_us) <= timeout):
# check amount of available characters
if self._uart.any() > 0:
# remember this time in microseconds
last_byte_ts = time.ticks_us()
# do not stop reading and appending the result to the buffer
# until the time between two frames elapsed
while True:
# WiPy only
# r = self._uart.readall()
time.sleep_us(100)
r = self._uart.read()
# if something has been read after the first iteration of
# this inner while loop (within self._inter_frame_delay)
if r is not None and len(r) > 0:
# append the new read stuff to the buffer
received_bytes.extend(r)
# update the timestamp of the last byte being read
last_byte_ts = time.ticks_us()
#print(last_byte_ts, received_bytes)
if time.ticks_diff(time.ticks_us(), last_byte_ts) >= self._inter_frame_delay:
break
# if something has been read before the overall timeout is reached
if len(received_bytes) > 0:
#print(time.ticks_diff(time.ticks_us(), start_us))
return received_bytes
#print(time.ticks_diff(time.ticks_us(), start_us))
# return the result in case the overall timeout has been reached
return received_bytes
def _send(self, modbus_pdu: bytes, slave_addr: int) -> None:
"""
Send Modbus frame via UART
If a flow control pin has been setup, it will be controlled accordingly
:param modbus_pdu: The modbus Protocol Data Unit
:type modbus_pdu: bytes
:param slave_addr: The slave address
:type slave_addr: int
"""
# modbus_adu: Modbus Application Data Unit
# consists of the Modbus PDU, with slave address prepended and checksum appended
modbus_adu = bytearray()
modbus_adu.append(slave_addr)
modbus_adu.extend(modbus_pdu)
modbus_adu.extend(self._calculate_crc16(modbus_adu))
if self._ctrlPin:
self._ctrlPin.on()
# wait until the control pin really changed
# 85-95us (ESP32 @ 160/240MHz)
time.sleep_us(200)
# the timing of this part is critical:
# - if we disable output too early,
# the command will not be received in full
# - if we disable output too late,
# the incoming response will lose some data at the beginning
# easiest to just wait for the bytes to be sent out on the wire
send_start_time = time.ticks_us()
# 360-400us @ 9600-115200 baud (measured) (ESP32 @ 160/240MHz)
self._uart.write(modbus_adu)
send_finish_time = time.ticks_us()
if self._has_uart_flush:
self._uart.flush()
time.sleep_us(self._t1char)
else:
sleep_time_us = (
self._t1char * len(modbus_adu) - # total frame time in us
time.ticks_diff(send_finish_time, send_start_time) +
100 # only required at baudrates above 57600, but hey 100us
)
time.sleep_us(sleep_time_us)
if self._ctrlPin:
self._ctrlPin.off()
def _send_receive(self,
modbus_pdu: bytes,
slave_addr: int,
count: bool) -> bytes:
"""
Send a modbus message and receive the reponse.
:param modbus_pdu: The modbus Protocol Data Unit
:type modbus_pdu: bytes
:param slave_addr: The slave address
:type slave_addr: int
:param count: The count
:type count: bool
:returns: Validated response content
:rtype: bytes
"""
# flush the Rx FIFO buffer
self._uart.read()
self._send(modbus_pdu=modbus_pdu, slave_addr=slave_addr)
return self._validate_resp_hdr(response=self._uart_read(),
slave_addr=slave_addr,
function_code=modbus_pdu[0],
count=count)
def _validate_resp_hdr(self,
response: bytearray,
slave_addr: int,
function_code: int,
count: bool) -> bytes:
"""
Validate the response header.
:param response: The response
:type response: bytearray
:param slave_addr: The slave address
:type slave_addr: int
:param function_code: The function code
:type function_code: int
:param count: The count
:type count: bool
:returns: Modbus response content
:rtype: bytes
"""
if len(response) == 0:
raise OSError('no data received from slave')
resp_crc = response[-Const.CRC_LENGTH:]
expected_crc = self._calculate_crc16(
response[0:len(response) - Const.CRC_LENGTH]
)
if ((resp_crc[0] is not expected_crc[0]) or
(resp_crc[1] is not expected_crc[1])):
raise OSError('invalid response CRC')
if (response[0] != slave_addr):
raise ValueError('wrong slave address')
if (response[1] == (function_code + Const.ERROR_BIAS)):
raise ValueError('slave returned exception code: {:d}'.
format(response[2]))
hdr_length = (Const.RESPONSE_HDR_LENGTH + 1) if count else \
Const.RESPONSE_HDR_LENGTH
return response[hdr_length:len(response) - Const.CRC_LENGTH]
def send_response(self,
slave_addr: int,
function_code: int,
request_register_addr: int,
request_register_qty: int,
request_data: list,
values: Optional[list] = None,
signed: bool = True) -> None:
"""
Send a response to a client.
:param slave_addr: The slave address
:type slave_addr: int
:param function_code: The function code
:type function_code: int
:param request_register_addr: The request register address
:type request_register_addr: int
:param request_register_qty: The request register qty
:type request_register_qty: int
:param request_data: The request data
:type request_data: list
:param values: The values
:type values: Optional[list]
:param signed: Indicates if signed
:type signed: bool
"""
modbus_pdu = functions.response(
function_code=function_code,
request_register_addr=request_register_addr,
request_register_qty=request_register_qty,
request_data=request_data,
value_list=values,
signed=signed
)
self._send(modbus_pdu=modbus_pdu, slave_addr=slave_addr)
def send_exception_response(self,
slave_addr: int,
function_code: int,
exception_code: int) -> None:
"""
Send an exception response to a client.
:param slave_addr: The slave address
:type slave_addr: int
:param function_code: The function code
:type function_code: int
:param exception_code: The exception code
:type exception_code: int
"""
modbus_pdu = functions.exception_response(
function_code=function_code,
exception_code=exception_code)
self._send(modbus_pdu=modbus_pdu, slave_addr=slave_addr)
def get_request(self,
unit_addr_list: List[int],
timeout: Optional[int] = None) -> Union[Request, None]:
"""
Check for request within the specified timeout
:param unit_addr_list: The unit address list
:type unit_addr_list: Optional[list]
:param timeout: The timeout
:type timeout: Optional[int]
:returns: A request object or None.
:rtype: Union[Request, None]
"""
req = self._uart_read_frame(timeout=timeout)
if len(req) < 8:
return None
if req[0] not in unit_addr_list:
return None
req_crc = req[-Const.CRC_LENGTH:]
req_no_crc = req[:-Const.CRC_LENGTH]
expected_crc = self._calculate_crc16(req_no_crc)
if (req_crc[0] != expected_crc[0]) or (req_crc[1] != expected_crc[1]):
return None
try:
request = Request(interface=self, data=req_no_crc)
except ModbusException as e:
self.send_exception_response(
slave_addr=req[0],
function_code=e.function_code,
exception_code=e.exception_code)
return None
return request
+416
View File
@@ -0,0 +1,416 @@
#!/usr/bin/env python
#
# Copyright (c) 2019, Pycom Limited.
#
# This software is licensed under the GNU GPL version 3 or any
# later version, with permitted additional terms. For more information
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#
# system packages
# import random
import struct
import socket
import time
# custom packages
from . import functions
from . import const as Const
from .common import Request, CommonModbusFunctions
from .common import ModbusException
from .modbus import Modbus
# typing not natively supported on MicroPython
from .typing import Optional, Tuple, Union
class ModbusTCP(Modbus):
"""Modbus TCP client class"""
def __init__(self):
super().__init__(
# set itf to TCPServer object, addr_list to None
TCPServer(),
None
)
def bind(self,
local_ip: str,
local_port: int = 502,
max_connections: int = 10) -> None:
"""
Bind IP and port for incomming requests
:param local_ip: IP of this device listening for requests
:type local_ip: str
:param local_port: Port of this device
:type local_port: int
:param max_connections: Number of maximum connections
:type max_connections: int
"""
self._itf.bind(local_ip, local_port, max_connections)
def get_bound_status(self) -> bool:
"""
Get the IP and port binding status.
:returns: The bound status, True if already bound, False otherwise.
:rtype: bool
"""
try:
return self._itf.get_is_bound()
except Exception:
return False
class TCP(CommonModbusFunctions):
"""
TCP class handling socket connections and parsing the Modbus data
:param slave_ip: IP of this device listening for requests
:type slave_ip: str
:param slave_port: Port of this device
:type slave_port: int
:param timeout: Socket timeout in seconds
:type timeout: float
"""
def __init__(self,
slave_ip: str,
slave_port: int = 502,
timeout: float = 5.0):
self._sock = socket.socket()
self.trans_id_ctr = 0
# print(socket.getaddrinfo(slave_ip, slave_port))
# [(2, 1, 0, '192.168.178.47', ('192.168.178.47', 502))]
self._sock.connect(socket.getaddrinfo(slave_ip, slave_port)[0][-1])
self._sock.settimeout(timeout)
def _create_mbap_hdr(self,
slave_addr: int,
modbus_pdu: bytes) -> Tuple[bytes, int]:
"""
Create a Modbus header.
:param slave_addr: The slave identifier
:type slave_addr: int
:param modbus_pdu: The modbus Protocol Data Unit
:type modbus_pdu: bytes
:returns: Modbus header and unique transaction ID
:rtype: Tuple[bytes, int]
"""
# only available on WiPy
# trans_id = machine.rng() & 0xFFFF
# use builtin function to generate random 24 bit integer
# trans_id = random.getrandbits(24) & 0xFFFF
# use incrementing counter as it's faster
trans_id = self.trans_id_ctr
self.trans_id_ctr += 1
mbap_hdr = struct.pack(
'>HHHB', trans_id, 0, len(modbus_pdu) + 1, slave_addr)
return mbap_hdr, trans_id
def _validate_resp_hdr(self,
response: bytearray,
trans_id: int,
slave_addr: int,
function_code: int,
count: bool = False) -> bytes:
"""
Validate the response header.
:param response: The response
:type response: bytearray
:param trans_id: The transaction identifier
:type trans_id: int
:param slave_addr: The slave identifier
:type slave_addr: int
:param function_code: The function code
:type function_code: int
:param count: The count
:type count: bool
:returns: Modbus response content
:rtype: bytes
"""
rec_tid, rec_pid, rec_len, rec_uid, rec_fc = struct.unpack(
'>HHHBB', response[:Const.MBAP_HDR_LENGTH + 1])
if (trans_id != rec_tid):
raise ValueError('wrong transaction ID')
if (rec_pid != 0):
raise ValueError('invalid protocol ID')
if (slave_addr != rec_uid):
raise ValueError('wrong slave ID')
if (rec_fc == (function_code + Const.ERROR_BIAS)):
raise ValueError('slave returned exception code: {:d}'.
format(rec_fc))
hdr_length = (Const.MBAP_HDR_LENGTH + 2) if count else \
(Const.MBAP_HDR_LENGTH + 1)
return response[hdr_length:]
def _send_receive(self,
slave_addr: int,
modbus_pdu: bytes,
count: bool) -> bytes:
"""
Send a modbus message and receive the reponse.
:param slave_addr: The slave identifier
:type slave_addr: int
:param modbus_pdu: The modbus PDU
:type modbus_pdu: bytes
:param count: The count
:type count: bool
:returns: Modbus data
:rtype: bytes
"""
mbap_hdr, trans_id = self._create_mbap_hdr(slave_addr=slave_addr,
modbus_pdu=modbus_pdu)
self._sock.send(mbap_hdr + modbus_pdu)
response = self._sock.recv(256)
modbus_data = self._validate_resp_hdr(response=response,
trans_id=trans_id,
slave_addr=slave_addr,
function_code=modbus_pdu[0],
count=count)
return modbus_data
class TCPServer(object):
"""Modbus TCP host class"""
def __init__(self):
self._sock = None
self._client_sock = None
self._is_bound = False
@property
def is_bound(self) -> bool:
"""
Get the IP and port binding status
:returns: True if bound to IP and port, False otherwise
:rtype: bool
"""
return self._is_bound
def get_is_bound(self) -> bool:
"""
Get the IP and port binding status, legacy support.
:returns: True if bound to IP and port, False otherwise
:rtype: bool
"""
return self._is_bound
def bind(self,
local_ip: str,
local_port: int = 502,
max_connections: int = 10):
"""
Bind IP and port for incomming requests
:param local_ip: IP of this device listening for requests
:type local_ip: str
:param local_port: Port of this device
:type local_port: int
:param max_connections: Number of maximum connections
:type max_connections: int
"""
if self._client_sock:
self._client_sock.close()
if self._sock:
self._sock.close()
self._sock = socket.socket()
# print(socket.getaddrinfo(local_ip, local_port))
# [(2, 1, 0, '192.168.178.47', ('192.168.178.47', 502))]
self._sock.bind(socket.getaddrinfo(local_ip, local_port)[0][-1])
self._sock.listen(max_connections)
self._is_bound = True
def _send(self, modbus_pdu: bytes, slave_addr: int) -> None:
"""
Send Modbus Protocol Data Unit to slave
:param modbus_pdu: The Modbus Protocol Data Unit
:type modbus_pdu: bytes
:param slave_addr: The slave address
:type slave_addr: int
"""
size = len(modbus_pdu)
fmt = 'B' * size
adu = struct.pack('>HHHB' + fmt, self._req_tid, 0, size + 1, slave_addr, *modbus_pdu)
self._client_sock.send(adu)
def send_response(self,
slave_addr: int,
function_code: int,
request_register_addr: int,
request_register_qty: int,
request_data: list,
values: Optional[list] = None,
signed: bool = True) -> None:
"""
Send a response to a client.
:param slave_addr: The slave address
:type slave_addr: int
:param function_code: The function code
:type function_code: int
:param request_register_addr: The request register address
:type request_register_addr: int
:param request_register_qty: The request register qty
:type request_register_qty: int
:param request_data: The request data
:type request_data: list
:param values: The values
:type values: Optional[list]
:param signed: Indicates if signed
:type signed: bool
"""
modbus_pdu = functions.response(function_code,
request_register_addr,
request_register_qty,
request_data,
values,
signed)
self._send(modbus_pdu, slave_addr)
def send_exception_response(self,
slave_addr: int,
function_code: int,
exception_code: int) -> None:
"""
Send an exception response to a client.
:param slave_addr: The slave address
:type slave_addr: int
:param function_code: The function code
:type function_code: int
:param exception_code: The exception code
:type exception_code: int
"""
modbus_pdu = functions.exception_response(function_code,
exception_code)
self._send(modbus_pdu, slave_addr)
def _accept_request(self,
accept_timeout: float,
unit_addr_list: list) -> Union[Request, None]:
"""
Accept, read and decode a socket based request
:param accept_timeout: The socket accept timeout
:type accept_timeout: float
:param unit_addr_list: The unit address list
:type unit_addr_list: list
"""
self._sock.settimeout(accept_timeout)
new_client_sock = None
try:
new_client_sock, client_address = self._sock.accept()
except OSError as e:
if e.args[0] != 110: # 110 = timeout expired
raise e
if new_client_sock is not None:
if self._client_sock is not None:
self._client_sock.close()
self._client_sock = new_client_sock
# recv() timeout, setting to 0 might lead to the following error
# "Modbus request error: [Errno 11] EAGAIN"
# This is a socket timeout error
self._client_sock.settimeout(0.5)
if self._client_sock is not None:
try:
req = self._client_sock.recv(128)
if len(req) == 0:
return None
req_header_no_uid = req[:Const.MBAP_HDR_LENGTH - 1]
self._req_tid, req_pid, req_len = struct.unpack('>HHH', req_header_no_uid)
req_uid_and_pdu = req[Const.MBAP_HDR_LENGTH - 1:Const.MBAP_HDR_LENGTH + req_len - 1]
except OSError:
# MicroPython raises an OSError instead of socket.timeout
# print("Socket OSError aka TimeoutError: {}".format(e))
return None
except Exception:
# print("Modbus request error:", e)
self._client_sock.close()
self._client_sock = None
return None
if (req_pid != 0):
# print("Modbus request error: PID not 0")
self._client_sock.close()
self._client_sock = None
return None
if ((unit_addr_list is not None) and (req_uid_and_pdu[0] not in unit_addr_list)):
return None
try:
return Request(self, req_uid_and_pdu)
except ModbusException as e:
self.send_exception_response(req[0],
e.function_code,
e.exception_code)
return None
def get_request(self,
unit_addr_list: Optional[list] = None,
timeout: int = None) -> Union[Request, None]:
"""
Check for request within the specified timeout
:param unit_addr_list: The unit address list
:type unit_addr_list: Optional[list]
:param timeout: The timeout
:type timeout: int
:returns: A request object or None.
:rtype: Union[Request, None]
:raises Exception: If no socket is configured and bound
"""
if self._sock is None:
raise Exception('Modbus TCP server not bound')
if timeout > 0:
start_ms = time.ticks_ms()
elapsed = 0
while True:
if self._client_sock is None:
accept_timeout = None if timeout is None else (timeout - elapsed) / 1000
else:
accept_timeout = 0
req = self._accept_request(accept_timeout, unit_addr_list)
if req:
return req
elapsed = time.ticks_diff(start_ms, time.ticks_ms())
if elapsed > timeout:
return None
else:
return self._accept_request(0, unit_addr_list)
+212
View File
@@ -0,0 +1,212 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Fake classes of typing module.
https://github.com/micropython/micropython-lib/issues/190
https://github.com/micropython/micropython-lib/blob/3d779b8ceab5b65b9f70accbcbb15ab3509eceb7/typing/typing.py
"""
class _Subscriptable():
def __getitem__(self, item):
return None
_subscriptable = _Subscriptable()
class Any:
pass
class NoReturn:
pass
class ClassVar:
pass
Union = _subscriptable
Optional = _subscriptable
class Generic:
pass
class NamedTuple:
pass
class Hashable:
pass
class Awaitable:
pass
class Coroutine:
pass
class AsyncIterable:
pass
class AsyncIterator:
pass
class Iterable:
pass
class Iterator:
pass
class Reversible:
pass
class Sized:
pass
class Container:
pass
class Collection:
pass
# class Callable:
# pass
Callable = _subscriptable
class AbstractSet:
pass
class MutableSet:
pass
class Mapping:
pass
class MutableMapping:
pass
class Sequence:
pass
class MutableSequence:
pass
class ByteString:
pass
Tuple = _subscriptable
List = _subscriptable
class Deque:
pass
class Set:
pass
class dict_keys:
pass
class FrozenSet:
pass
class MappingView:
pass
class KeysView:
pass
class ItemsView:
pass
class ValuesView:
pass
class ContextManager:
pass
class AsyncContextManager:
pass
Dict = _subscriptable
class DefaultDict:
pass
class Counter:
pass
class ChainMap:
pass
class Generator:
pass
class AsyncGenerator:
pass
class Type:
pass
def cast(typ, val):
return val
def _overload_dummy(*args, **kwds):
"""Helper for @overload to raise when called."""
raise NotImplementedError(
"You should not call an overloaded function. "
"A series of @overload-decorated functions "
"outside a stub module should always be followed "
"by an implementation that is not @overload-ed."
)
def overload():
return _overload_dummy
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
__version_info__ = ("2", "3", "7")
__version__ = '.'.join(__version_info__)
+88
View File
@@ -0,0 +1,88 @@
# wget http://file.ofs.com/hv/script/umqtt/mqtt.py script/umqtt/mqtt.py
# mqtt_client.py 测试
from script.umqtt.simple import MQTTClient
from binascii import hexlify
import machine
import _thread
import time, sys
class MQTTClientThread:
def __init__(self, server, client_id):
self.server = server
self.client_id = client_id
self.running = False
self.send_list = []
self.receive_list = []
self.lock = _thread.allocate_lock()
self.client = MQTTClient(client_id, server)
def sub_cb(self, topic, msg):
with self.lock:
self.receive_list.append((topic, msg)) # 将接收到的消息添加到接收列表
print("Received: {}".format((topic, msg)))
def run(self):
try:
self.client.set_callback(self.sub_cb)
self.client.connect()
print("Connected to {}".format(self.server))
for topic in self.sub_list:
self.client.subscribe(topic)
self.running = True
while self.running:
self.client.check_msg()
self.process_messages()
print("mqtt exit")
except Exception as e:
sys.print_exception(e)
finally:
_thread.exit()
self.client.disconnect()
print("mqtt stop")
def process_messages(self):
with self.lock:
while self.send_list:
topic, msg, qos = self.send_list.pop(0) # 从发送列表中取出第一个消息
self.client.publish(topic, msg, qos)
# print("Sent: {} to topic: {} with QoS: {}".format(msg, topic, qos))
def start(self):
if not self.running:
_thread.stack_size(18192)
_thread.start_new_thread(self.run, ())
def stop(self):
self.running = False
def send_message(self, topic, message, qos=0):
with self.lock:
self.send_list.append((topic, message, qos)) # 将消息添加到发送列表
# print("Queued for sending: {}".format((topic, message, qos)))
def take_message(self):
with self.lock:
if self.receive_list:
return self.receive_list.pop(0) # 返回并移除接收列表的第一个消息
else:
return None # 如果没有消息,返回 None
def start_mqtt_client(params={}):
server = params['broker']['ip']
client_id = params['broker']['clientid'] + hexlify(machine.unique_id()).decode()[0:8]
mqtt_client = MQTTClientThread(server, client_id)
mqtt_client.client.port = params['broker']['port']
mqtt_client.client.user = params['broker']['user']
mqtt_client.client.pswd = params['broker']['passwd']
mqtt_client.sub_list = params['topic']['sub']
mqtt_client.start()
return mqtt_client
+220
View File
@@ -0,0 +1,220 @@
import socket
import struct
from binascii import hexlify
class MQTTException(Exception):
pass
class MQTTClient:
def __init__(
self,
client_id,
server,
port=0,
user=None,
password=None,
keepalive=0,
ssl=None,
ssl_params={},
):
if port == 0:
port = 8883 if ssl else 1883
self.client_id = client_id
self.sock = None
self.server = server
self.port = port
self.ssl = ssl
self.ssl_params = ssl_params
self.pid = 0
self.cb = None
self.user = user
self.pswd = password
self.keepalive = keepalive
self.lw_topic = None
self.lw_msg = None
self.lw_qos = 0
self.lw_retain = False
def _send_str(self, s):
self.sock.write(struct.pack("!H", len(s)))
self.sock.write(s)
def _recv_len(self):
n = 0
sh = 0
while 1:
b = self.sock.read(1)[0]
n |= (b & 0x7F) << sh
if not b & 0x80:
return n
sh += 7
def set_callback(self, f):
self.cb = f
def set_last_will(self, topic, msg, retain=False, qos=0):
assert 0 <= qos <= 2
assert topic
self.lw_topic = topic
self.lw_msg = msg
self.lw_qos = qos
self.lw_retain = retain
def connect(self, clean_session=True, timeout=None):
self.sock = socket.socket()
self.sock.settimeout(timeout)
addr = socket.getaddrinfo(self.server, self.port)[0][-1]
self.sock.connect(addr)
if self.ssl is True:
# Legacy support for ssl=True and ssl_params arguments.
import ssl
self.sock = ssl.wrap_socket(self.sock, **self.ssl_params)
elif self.ssl:
self.sock = self.ssl.wrap_socket(self.sock, server_hostname=self.server)
premsg = bytearray(b"\x10\0\0\0\0\0")
msg = bytearray(b"\x04MQTT\x04\x02\0\0")
sz = 10 + 2 + len(self.client_id)
msg[6] = clean_session << 1
if self.user:
sz += 2 + len(self.user) + 2 + len(self.pswd)
msg[6] |= 0xC0
if self.keepalive:
assert self.keepalive < 65536
msg[7] |= self.keepalive >> 8
msg[8] |= self.keepalive & 0x00FF
if self.lw_topic:
sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
msg[6] |= self.lw_retain << 5
i = 1
while sz > 0x7F:
premsg[i] = (sz & 0x7F) | 0x80
sz >>= 7
i += 1
premsg[i] = sz
self.sock.write(premsg, i + 2)
self.sock.write(msg)
# print(hex(len(msg)), hexlify(msg, ":"))
self._send_str(self.client_id)
if self.lw_topic:
self._send_str(self.lw_topic)
self._send_str(self.lw_msg)
if self.user:
self._send_str(self.user)
self._send_str(self.pswd)
resp = self.sock.read(4)
assert resp[0] == 0x20 and resp[1] == 0x02
if resp[3] != 0:
raise MQTTException(resp[3])
return resp[2] & 1
def disconnect(self):
self.sock.write(b"\xe0\0")
self.sock.close()
def ping(self):
self.sock.write(b"\xc0\0")
def publish(self, topic, msg, retain=False, qos=0):
pkt = bytearray(b"\x30\0\0\0")
pkt[0] |= qos << 1 | retain
sz = 2 + len(topic) + len(msg)
if qos > 0:
sz += 2
assert sz < 2097152
i = 1
while sz > 0x7F:
pkt[i] = (sz & 0x7F) | 0x80
sz >>= 7
i += 1
pkt[i] = sz
# print(hex(len(pkt)), hexlify(pkt, ":"))
self.sock.write(pkt, i + 1)
self._send_str(topic)
if qos > 0:
self.pid += 1
pid = self.pid
struct.pack_into("!H", pkt, 0, pid)
self.sock.write(pkt, 2)
self.sock.write(msg)
if qos == 1:
while 1:
op = self.wait_msg()
if op == 0x40:
sz = self.sock.read(1)
assert sz == b"\x02"
rcv_pid = self.sock.read(2)
rcv_pid = rcv_pid[0] << 8 | rcv_pid[1]
if pid == rcv_pid:
return
elif qos == 2:
assert 0
def subscribe(self, topic, qos=0):
assert self.cb is not None, "Subscribe callback is not set"
pkt = bytearray(b"\x82\0\0\0")
self.pid += 1
struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid)
# print(hex(len(pkt)), hexlify(pkt, ":"))
self.sock.write(pkt)
self._send_str(topic)
self.sock.write(qos.to_bytes(1, "little"))
while 1:
op = self.wait_msg()
if op == 0x90:
resp = self.sock.read(4)
# print(resp)
assert resp[1] == pkt[2] and resp[2] == pkt[3]
if resp[3] == 0x80:
raise MQTTException(resp[3])
return
# Wait for a single incoming MQTT message and process it.
# Subscribed messages are delivered to a callback previously
# set by .set_callback() method. Other (internal) MQTT
# messages processed internally.
def wait_msg(self):
res = self.sock.read(1)
self.sock.setblocking(True)
if res is None:
return None
if res == b"":
raise OSError(-1)
if res == b"\xd0": # PINGRESP
sz = self.sock.read(1)[0]
assert sz == 0
return None
op = res[0]
if op & 0xF0 != 0x30:
return op
sz = self._recv_len()
topic_len = self.sock.read(2)
topic_len = (topic_len[0] << 8) | topic_len[1]
topic = self.sock.read(topic_len)
sz -= topic_len + 2
if op & 6:
pid = self.sock.read(2)
pid = pid[0] << 8 | pid[1]
sz -= 2
msg = self.sock.read(sz)
self.cb(topic, msg)
if op & 6 == 2:
pkt = bytearray(b"\x40\x02\0\0")
struct.pack_into("!H", pkt, 2, pid)
self.sock.write(pkt)
elif op & 6 == 4:
assert 0
return op
# Checks whether a pending message from server is available.
# If not, returns immediately with None. Otherwise, does
# the same processing as wait_msg.
def check_msg(self):
self.sock.setblocking(False)
return self.wait_msg()
+1
View File
@@ -0,0 +1 @@
wget http://file.ofs.com/hv/main.py main.py
+8
View File
@@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
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.
+377
View File
@@ -0,0 +1,377 @@
<h3>
<p align="center">
Also check out the new ESP32 MPY-Jama free IDE and the latest MicroWebSrv2 below:
</p>
</h3>
<p align="center">
<a href="https://github.com/jczic/ESP32-MPY-Jama"><img src="https://github.com/jczic/ESP32-MPY-Jama/raw/master/img/ESP32%20MPY-Jama%20NEW.png" alt="New microWebSrv2" width="350" valign="middle"></a>                  
<a href="https://github.com/jczic/MicroWebSrv2"><img src="microWebSrv2.png" alt="New microWebSrv2" width="350" valign="middle"></a>
</p>
---
<br />
### MicroWebSrv is a micro HTTP Web server that supports WebSockets, html/python language templating and routing handlers, for MicroPython (principally used on ESP32 and [Pycom](http://www.pycom.io) modules. Now supports all variants of [Pyboard D-series](https://store.micropython.org/category/pyboard%20D-series) from the makers of Micropython)
![HC²](hc2.png "HC²")
Very easy to integrate and very light with 3 files only :
- `"microWebSrv.py"` - The Web server
- `"microWebSocket.py"` - The optional support of WebSockets
- `"microWebTemplate.py"` - The optional templating language for **.pyhtml** rendered pages
Mini tuto in video by rdagger68 :
- [https://www.youtube.com/watch?v=xscBwC1SrF4](https://www.youtube.com/watch?v=xscBwC1SrF4)
Simple but effective :
- Use it to embed a cool Web site in yours modules
- Handle GET, POST, ... requests to interract with user and configure options
- Exchange in JSON format on HTTP methods to make an embedded fullREST API
- Serve files on the fly to export any data to the user
- Use routes and variable route handlers
- Play with AjAX to interact speedly with a Web application
- Make it a captive portal simply
- Use WebSockets for fast and powerful data exchange
- Make html/python files for rendering more efficient web pages
### Using *microWebSrv* main class :
| Name | Function |
| - | - |
| Constructor | `mws = MicroWebSrv(routeHandlers=None, port=80, bindIP='0.0.0.0', webPath="/flash/www")` |
| Start Web server | `mws.Start(threaded=True)` |
| Stop Web server | `mws.Stop()` |
| Check if Web server is running | `mws.IsStarted()` |
| Set URL location for not found page | `mws.SetNotFoundPageUrl(url=None)` |
| Get mime type from file extention | `mws.GetMimeTypeFromFilename(filename)` |
| Get handler function from route | `(routeHandler, routeArgs) = mws.GetRouteHandler(resUrl, method)` |
| Callback function to enable and accept WebSockets | `mws.AcceptWebSocketCallback = _acptWS` `_acptWS(webSocket, httpClient) { }` |
| Maximum length of memory allocated to receive WebSockets data (1024 by default) | `mws.MaxWebSocketRecvLen` |
| New thread used for each WebSocket connection (True by default) | `mws.WebSocketThreaded` |
| Escape string to HTML usage | `MicroWebSrv.HTMLEscape(s)` |
### Basic example :
```python
from microWebSrv import MicroWebSrv
mws = MicroWebSrv() # TCP port 80 and files in /flash/www
mws.Start(threaded=True) # Starts server in a new thread
```
### Using as captive portal :
```python
# To intercept all not found queries and redirect it,
mws.SetNotFoundPageUrl("http://my-device.wifi")
```
- Can be used with [MicroDNSSrv](http://microdnssrv.hc2.fr) easily.
### Using route handlers example :
```python
routeHandlers = [
( "relative_url_route_1", "METHOD", handlerFunc_1 ),
( "relative_url_route_2", "METHOD", handlerFunc_2 ),
( ... )
]
```
```python
def handlerFunc_1(httpClient, httpResponse, routeArgs=None) :
print("In HTTP handler 1")
def handlerFunc_2(httpClient, httpResponse, routeArgs=None) :
print("In HTTP handler 2")
```
### Using directly route handlers decorators example :
```python
@MicroWebSrv.route('/get-test')
def handlerFuncGet(httpClient, httpResponse) :
print("In GET-TEST HTTP")
@MicroWebSrv.route('/post-test', 'POST')
def handlerFuncPost(httpClient, httpResponse) :
print("In POST-TEST HTTP")
```
### Using variable routes example :
```python
routeHandlers = [
( "/edit/<testid>/<testpath>", "GET", handlerFuncEdit ),
( ... )
]
def handlerFuncEdit(httpClient, httpResponse, routeArgs) :
print("In EDIT HTTP variable route :")
print(" - testid = %s" % routeArgs['testid'])
print(" - testpath = %s" % routeArgs['testpath'])
```
Or direclty with route handler decorator :
```python
@MicroWebSrv.route('/edit/<testid>/<testpath>')
def handlerFuncEdit(httpClient, httpResponse, routeArgs) :
print("In EDIT HTTP variable route :")
print(" - testid = %s" % routeArgs['testid'])
print(" - testpath = %s" % routeArgs['testpath'])
```
### Using *httpClient* class in a route handler function :
| Name | Function |
| - | - |
| Get MicroWebSrv class | `httpClient.GetServer()` |
| Get client address as tuple | `httpClient.GetAddr()` |
| Get client IP address | `httpClient.GetIPAddr()` |
| Get client TCP port | `httpClient.GetPort()` |
| Get client request method | `httpClient.GetRequestMethod()` |
| Get client request total path | `httpClient.GetRequestTotalPath()` |
| Get client request ressource path | `httpClient.GetRequestPath()` |
| Get client request query string | `httpClient.GetRequestQueryString()` |
| Get client request query parameters as list | `httpClient.GetRequestQueryParams()` |
| Get client request headers as list | `httpClient.GetRequestHeaders()` |
| Get client request content type | `httpClient.GetRequestContentType()` |
| Get client request content length | `httpClient.GetRequestContentLength()` |
| Get client request content | `httpClient.ReadRequestContent(size=None)` |
| Get client request form data as list | `httpClient.ReadRequestPostedFormData()` |
| Get client request as JSON object | `httpClient.ReadRequestContentAsJSON()` |
### Using *httpResponse* class in a route handler function :
| Name | Function |
| - | - |
| Write switching protocols response | `httpResponse.WriteSwitchProto(upgrade, headers=None)` |
| Write generic response | `httpResponse.WriteResponse(code, headers, contentType, contentCharset, content)` |
| Write PyHTML rendered response page | `httpResponse.WriteResponsePyHTMLFile(filepath, headers=None, vars=None)` |
| Write file directly as response | `httpResponse.WriteResponseFile(filepath, contentType=None, headers=None)` |
| Write attached file as response | `httpResponse.WriteResponseFileAttachment(filepath, attachmentName, headers=None)` |
| Write OK response | `httpResponse.WriteResponseOk(headers=None, contentType=None, contentCharset=None, content=None)` |
| Write JSON object as OK response | `httpResponse.WriteResponseJSONOk(obj=None, headers=None)` |
| Write redirect response | `httpResponse.WriteResponseRedirect(location)` |
| Write error response | `httpResponse.WriteResponseError(code)` |
| Write JSON object as error response | `httpResponse.WriteResponseJSONError(code, obj=None)` |
| Write bad request response | `httpResponse.WriteResponseBadRequest()` |
| Write forbidden response | `httpResponse.WriteResponseForbidden()` |
| Write not found response | `httpResponse.WriteResponseNotFound()` |
| Write method not allowed response | `httpResponse.WriteResponseMethodNotAllowed()` |
| Write internal server error response | `httpResponse.WriteResponseInternalServerError()` |
| Write not implemented response | `httpResponse.WriteResponseNotImplemented()` |
### Using route handler function example :
```python
def _httpHandlerTestPost(httpClient, httpResponse) :
formData = httpClient.ReadRequestPostedFormData()
firstname = formData["firstname"]
lastname = formData["lastname"]
content = """\
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>TEST POST</title>
</head>
<body>
<h1>TEST POST</h1>
Firstname = %s<br />
Lastname = %s<br />
</body>
</html>
""" % ( MicroWebSrv.HTMLEscape(firstname),
MicroWebSrv.HTMLEscape(lastname) )
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )
```
### Known mime types (content types) :
| File extension | Mime type |
| - | - |
| .txt | text/plain |
| .htm | text/html |
| .html | text/html |
| .css | text/css |
| .csv | text/csv |
| .js | application/javascript |
| .xml | application/xml |
| .xhtml | application/xhtml+xml |
| .json | application/json |
| .zip | application/zip |
| .pdf | application/pdf |
| .ts | application/typescript |
| .woff | font/woff |
| .woff2 | font/woff2 |
| .ttf | font/ttf |
| .otf | font/otf |
| .jpg | image/jpeg |
| .jpeg | image/jpeg |
| .png | image/png |
| .gif | image/gif |
| .svg | image/svg+xml |
| .ico | image/x-icon |
### Default index pages order (for http://hostname/) :
| Filename |
| - |
| index.pyhtml |
| index.html |
| index.htm |
| default.pyhtml |
| default.html |
| default.htm |
### Using optional module *microWebSocket* to connect WebSockets :
- File `"microWebSocket.py"` must be present to activate WebSockets support
### Enable and accept WebSockets :
```python
from microWebSrv import MicroWebSrv
mws = MicroWebSrv() # TCP port 80 and files in /flash/www
mws.MaxWebSocketRecvLen = 256 # Default is set to 1024
mws.WebSocketThreaded = False # WebSockets without new threads
mws.AcceptWebSocketCallback = _acceptWebSocketCallback # Function to receive WebSockets
mws.Start(threaded=True) # Starts server in a new thread
```
| Name | Function |
| - | - |
| Callback function to receive text message | `ws.RecvTextCallback = func(webSocket, msg)` |
| Callback function to receive binary data | `ws.RecvBinaryCallback = func(webSocket, data)` |
| Callback function when connection was closed | `ws.ClosedCallback = func(webSocket)` |
| Send a text message | `ws.SendText(msg)` |
| Send a binary message | `ws.SendBinary(data)` |
| Check connection state | `ws.IsClosed()` |
| Close the connection | `ws.Close()` |
### Basic example of callback functions :
```python
def _acceptWebSocketCallback(webSocket, httpClient) :
print("WS ACCEPT")
webSocket.RecvTextCallback = _recvTextCallback
webSocket.RecvBinaryCallback = _recvBinaryCallback
webSocket.ClosedCallback = _closedCallback
def _recvTextCallback(webSocket, msg) :
print("WS RECV TEXT : %s" % msg)
webSocket.SendText("Reply for %s" % msg)
def _recvBinaryCallback(webSocket, data) :
print("WS RECV DATA : %s" % data)
def _closedCallback(webSocket) :
print("WS CLOSED")
```
### Using optional module *microWebTemplate* for *.pyhtml* rendered pages :
- File `"microWebTemplate.py"` must be present to activate **.pyhtml** pages
- Pages will be rendered in HTML with integrated MicroPython code
| Instruction | Schema |
| - | - |
| PY | `{{ py }}` *MicroPython code* `{{ end }}` |
| IF | `{{ if` *MicroPython condition* `}}` *html bloc* `{{ end }}` |
| ELIF | `{{ elif` *MicroPython condition* `}}` *html bloc* `{{ end }}` |
| ELSE | `{{ else }}` *html bloc* `{{ end }}` |
| FOR | `{{ for` *identifier* `in` *MicroPython iterator* `}}` *html bloc* `{{ end }}` |
| INCLUDE | `{{ include` *pyhtml_filename* `}}` |
| ?   | `{{` *MicroPython expression* `}}` |
### Using {{ py }} :
```python
{{ py }}
import machine
from utime import sleep
test = 123
def testFunc(x) :
return 2 * x
{{ end }}
```
### Using {{ if ... }} :
```python
{{ if testFunc(5) <= 3 }}
<span>titi</span>
{{ elif testFunc(10) >= 15 }}
<span>tata</span>
{{ else }}
<span>I like the number {{ test }} !</span>
{{ end }}
```
### Using {{ for ... }} :
```python
{{ for toto in range(testFunc(3)) }}
<div>toto x 10 equal {{ toto * 10 }}</div>
<hr />
{{ end }}
```
### Using {{ include ... }} :
```python
{{ include myTemplate.pyhtml }}
```
### Example of a .pyhtml file :
```html
<html>
<head>
<title>TEST PYHTML</title>
</head>
<body>
<h1>BEGIN</h1>
{{ py }}
def _testFunction(x) :
return "IN TEST FUNCTION %s" % x
{{ end }}
<div style="background-color: black; color: white;">
{{ for toto in range(3) }}
This is an HTML test...<br />
TOTO = {{ toto + 1 }} !<br />
{{ for toto2 in range(3) }}
TOTO2 = {{ _testFunction(toto2) }}
{{ end }}
Ok good.<br />
{{ end }}
</div>
{{ _testFunction(100) }}<br />
<br />
{{ if 2+5 < 3 }}
IN IF (1)
{{ elif 10+15 != 25 }}
IN ELIF (2)
{{ elif 10+15 == 25 }}
IN ELIF (3)
{{ else }}
IN ELSE (4)
{{ end }}
</body>
</html>
```
<a name="author"></a>
## :wink: &nbsp;Author
**Jean-Christophe Bos** (:fr:)
- GitHub: *[@jczic](https://github.com/jczic)*
- Email: *<jczic.bos@gmail.com>*
- Profil: *[LinkedIn](https://www.linkedin.com/in/jczic)*
- Music: *[SoundCloud](https://soundcloud.com/jczic/sets/electro-pulse)*
*[Spotify](https://open.spotify.com/album/5fUd57GcAIcdUn9NX3fviG)*
*[YouTube](https://www.youtube.com/playlist?list=PL9CsGuMbcLaU02VKS7jtR6LaDNpq7MZEq)*
### By JC`zic for [HC²](https://www.hc2.fr) ;')
*Keep it simple, stupid* :+1:
+2
View File
@@ -0,0 +1,2 @@
show_downloads: true
theme: jekyll-theme-midnight
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

+121
View File
@@ -0,0 +1,121 @@
from microWebSrv import MicroWebSrv
# ----------------------------------------------------------------------------
@MicroWebSrv.route('/test')
def _httpHandlerTestGet(httpClient, httpResponse) :
content = """\
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8" />
<title>TEST GET</title>
</head>
<body>
<h1>TEST GET</h1>
Client IP address = %s
<br />
<form action="/test" method="post" accept-charset="ISO-8859-1">
First name: <input type="text" name="firstname"><br />
Last name: <input type="text" name="lastname"><br />
<input type="submit" value="Submit">
</form>
</body>
</html>
""" % httpClient.GetIPAddr()
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )
@MicroWebSrv.route('/test', 'POST')
def _httpHandlerTestPost(httpClient, httpResponse) :
formData = httpClient.ReadRequestPostedFormData()
firstname = formData["firstname"]
lastname = formData["lastname"]
content = """\
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8" />
<title>TEST POST</title>
</head>
<body>
<h1>TEST POST</h1>
Firstname = %s<br />
Lastname = %s<br />
</body>
</html>
""" % ( MicroWebSrv.HTMLEscape(firstname),
MicroWebSrv.HTMLEscape(lastname) )
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )
@MicroWebSrv.route('/edit/<index>') # <IP>/edit/123 -> args['index']=123
@MicroWebSrv.route('/edit/<index>/abc/<foo>') # <IP>/edit/123/abc/bar -> args['index']=123 args['foo']='bar'
@MicroWebSrv.route('/edit') # <IP>/edit -> args={}
def _httpHandlerEditWithArgs(httpClient, httpResponse, args={}) :
content = """\
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8" />
<title>TEST EDIT</title>
</head>
<body>
"""
content += "<h1>EDIT item with {} variable arguments</h1>"\
.format(len(args))
if 'index' in args :
content += "<p>index = {}</p>".format(args['index'])
if 'foo' in args :
content += "<p>foo = {}</p>".format(args['foo'])
content += """
</body>
</html>
"""
httpResponse.WriteResponseOk( headers = None,
contentType = "text/html",
contentCharset = "UTF-8",
content = content )
# ----------------------------------------------------------------------------
def _acceptWebSocketCallback(webSocket, httpClient) :
print("WS ACCEPT")
webSocket.RecvTextCallback = _recvTextCallback
webSocket.RecvBinaryCallback = _recvBinaryCallback
webSocket.ClosedCallback = _closedCallback
def _recvTextCallback(webSocket, msg) :
print("WS RECV TEXT : %s" % msg)
webSocket.SendText("Reply for %s" % msg)
def _recvBinaryCallback(webSocket, data) :
print("WS RECV DATA : %s" % data)
def _closedCallback(webSocket) :
print("WS CLOSED")
# ----------------------------------------------------------------------------
#routeHandlers = [
# ( "/test", "GET", _httpHandlerTestGet ),
# ( "/test", "POST", _httpHandlerTestPost )
#]
srv = MicroWebSrv(webPath='/web_root/web_admin/')
srv.MaxWebSocketRecvLen = 256
srv.WebSocketThreaded = False
srv.AcceptWebSocketCallback = _acceptWebSocketCallback
srv.Start()
# ----------------------------------------------------------------------------
+284
View File
@@ -0,0 +1,284 @@
"""
The MIT License (MIT)
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from hashlib import sha1
from binascii import b2a_base64
from struct import pack
from _thread import start_new_thread, allocate_lock
import gc
class MicroWebSocket :
# ============================================================================
# ===( Constants )============================================================
# ============================================================================
_handshakeSign = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
_opContFrame = 0x0
_opTextFrame = 0x1
_opBinFrame = 0x2
_opCloseFrame = 0x8
_opPingFrame = 0x9
_opPongFrame = 0xA
_msgTypeText = 1
_msgTypeBin = 2
# ============================================================================
# ===( Utils )===============================================================
# ============================================================================
@staticmethod
def _tryAllocByteArray(size) :
for x in range(10) :
try :
gc.collect()
return bytearray(size)
except :
pass
return None
# ----------------------------------------------------------------------------
@staticmethod
def _tryStartThread(func, args=()) :
for x in range(10) :
try :
gc.collect()
start_new_thread(func, args)
return True
except :
global _mws_thread_id
try :
_mws_thread_id += 1
except :
_mws_thread_id = 0
try :
start_new_thread('MWS_THREAD_%s' % _mws_thread_id, func, args)
return True
except :
pass
return False
# ============================================================================
# ===( Constructor )==========================================================
# ============================================================================
def __init__(self, socket, httpClient, httpResponse, maxRecvLen, threaded, acceptCallback) :
self._socket = socket
self._httpCli = httpClient
self._closed = True
self._lock = allocate_lock()
self.RecvTextCallback = None
self.RecvBinaryCallback = None
self.ClosedCallback = None
if hasattr(socket, 'read'): # MicroPython
self._socketfile = self._socket
else: # CPython
self._socketfile = self._socket.makefile('rwb')
if self._handshake(httpResponse) :
self._ctrlBuf = MicroWebSocket._tryAllocByteArray(0x7D)
self._msgBuf = MicroWebSocket._tryAllocByteArray(maxRecvLen)
if self._ctrlBuf and self._msgBuf :
self._msgType = None
self._msgLen = 0
if threaded :
if MicroWebSocket._tryStartThread(self._wsProcess, (acceptCallback, )) :
return
else :
self._wsProcess(acceptCallback)
return
print("MicroWebSocket : Out of memory on new WebSocket connection.")
try :
if self._socketfile is not self._socket:
self._socketfile.close()
self._socket.close()
except :
pass
# ============================================================================
# ===( Functions )============================================================
# ============================================================================
def _handshake(self, httpResponse) :
try :
key = self._httpCli.GetRequestHeaders().get('sec-websocket-key', None)
if key :
key += self._handshakeSign
r = sha1(key.encode()).digest()
r = b2a_base64(r).decode().strip()
httpResponse.WriteSwitchProto("websocket", { "Sec-WebSocket-Accept" : r })
return True
except :
pass
return False
# ----------------------------------------------------------------------------
def _wsProcess(self, acceptCallback) :
self._socket.settimeout(3600)
self._closed = False
try :
acceptCallback(self, self._httpCli)
except Exception as ex :
print("MicroWebSocket : Error on accept callback (%s)." % str(ex))
while not self._closed :
if not self._receiveFrame() :
self.Close()
if self.ClosedCallback :
try :
self.ClosedCallback(self)
except Exception as ex :
print("MicroWebSocket : Error on closed callback (%s)." % str(ex))
# ----------------------------------------------------------------------------
def _receiveFrame(self) :
try :
b = self._socketfile.read(2)
if not b or len(b) != 2 :
return False
fin = b[0] & 0x80 > 0
opcode = b[0] & 0x0F
masked = b[1] & 0x80 > 0
length = b[1] & 0x7F
if opcode == self._opContFrame and not self._msgType :
return False
elif opcode == self._opTextFrame :
self._msgType = self._msgTypeText
elif opcode == self._opBinFrame :
self._msgType = self._msgTypeBin
if length == 0x7E :
b = self._socketfile.read(2)
if not b or len(b) != 2 :
return False
length = (b[0] << 8) + b[1]
elif length == 0x7F :
return False
mask = self._socketfile.read(4) if masked else None
if masked and (not mask or len(mask) != 4) :
return False
if opcode == self._opContFrame or \
opcode == self._opTextFrame or \
opcode == self._opBinFrame :
if length > 0 :
buf = memoryview(self._msgBuf)[self._msgLen:]
if length > len(buf) :
return False
x = self._socketfile.readinto(buf[0:length])
if x != length :
return False
if masked :
for i in range(length) :
idx = self._msgLen + i
self._msgBuf[idx] ^= mask[i%4]
self._msgLen += length
if fin :
b = bytes(memoryview(self._msgBuf)[:self._msgLen])
if self._msgType == self._msgTypeText :
if self.RecvTextCallback :
try :
self.RecvTextCallback(self, b.decode())
except Exception as ex :
print("MicroWebSocket : Error on recv text callback (%s)." % str(ex))
else :
if self.RecvBinaryCallback :
try :
self.RecvBinaryCallback(self, b)
except Exception as ex :
print("MicroWebSocket : Error on recv binary callback (%s)." % str(ex))
self._msgType = None
self._msgLen = 0
else :
return False
elif opcode == self._opPingFrame :
if length > len(self._ctrlBuf) :
return False
if length > 0 :
x = self._socketfile.readinto(self._ctrlBuf[0:length])
if x != length :
return False
pingData = memoryview(self._ctrlBuf)[:length]
else :
pingData = None
self._sendFrame(self._opPongFrame, pingData)
elif opcode == self._opCloseFrame :
self.Close()
except :
return False
return True
# ----------------------------------------------------------------------------
def _sendFrame(self, opcode, data=None, fin=True) :
if not self._closed and opcode >= 0x00 and opcode <= 0x0F :
dataLen = 0 if not data else len(data)
if dataLen <= 0xFFFF :
b1 = (0x80 | opcode) if fin else opcode
b2 = 0x7E if dataLen >= 0x7E else dataLen
self._lock.acquire()
try :
if self._socketfile.write(pack('>BB', b1, b2)) == 2 :
if dataLen > 0 :
if dataLen >= 0x7E :
self._socketfile.write(pack('>H', dataLen))
ret = self._socketfile.write(data) == dataLen
else :
ret = True
if self._socketfile is not self._socket :
self._socketfile.flush() # CPython needs flush to continue protocol
self._lock.release()
return ret
except :
pass
self._lock.release()
return False
# ----------------------------------------------------------------------------
def SendText(self, msg) :
return self._sendFrame(self._opTextFrame, msg.encode())
# ----------------------------------------------------------------------------
def SendBinary(self, data) :
return self._sendFrame(self._opBinFrame, data)
# ----------------------------------------------------------------------------
def IsClosed(self) :
return self._closed
# ----------------------------------------------------------------------------
def Close(self) :
if not self._closed :
try :
self._sendFrame(self._opCloseFrame)
if self._socketfile is not self._socket:
self._socketfile.close()
self._socket.close()
self._closed = True
except :
pass
# ============================================================================
# ============================================================================
# ============================================================================
+880
View File
@@ -0,0 +1,880 @@
"""
The MIT License (MIT)
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from json import loads, dumps
from os import stat
from _thread import start_new_thread
import socket
import gc
import re
try :
from microWebTemplate import MicroWebTemplate
except :
pass
try :
from microWebSocket import MicroWebSocket
except :
pass
class MicroWebSrvRoute :
def __init__(self, route, method, func, routeArgNames, routeRegex) :
self.route = route
self.method = method
self.func = func
self.routeArgNames = routeArgNames
self.routeRegex = routeRegex
class MicroWebSrv :
# ============================================================================
# ===( Constants )============================================================
# ============================================================================
_indexPages = [
"index.pyhtml",
"index.html",
"index.htm",
"default.pyhtml",
"default.html",
"default.htm"
]
_mimeTypes = {
".txt" : "text/plain",
".htm" : "text/html",
".html" : "text/html",
".css" : "text/css",
".csv" : "text/csv",
".js" : "application/javascript",
".xml" : "application/xml",
".xhtml" : "application/xhtml+xml",
".json" : "application/json",
".zip" : "application/zip",
".pdf" : "application/pdf",
".ts" : "application/typescript",
".woff" : "font/woff",
".woff2" : "font/woff2",
".ttf" : "font/ttf",
".otf" : "font/otf",
".jpg" : "image/jpeg",
".jpeg" : "image/jpeg",
".png" : "image/png",
".gif" : "image/gif",
".svg" : "image/svg+xml",
".ico" : "image/x-icon"
}
_html_escape_chars = {
"&" : "&amp;",
'"' : "&quot;",
"'" : "&apos;",
">" : "&gt;",
"<" : "&lt;"
}
_pyhtmlPagesExt = '.pyhtml'
# ============================================================================
# ===( Class globals )=======================================================
# ============================================================================
_docoratedRouteHandlers = []
# ============================================================================
# ===( Utils )===============================================================
# ============================================================================
@classmethod
def route(cls, url, method='GET'):
""" Adds a route handler function to the routing list """
def route_decorator(func):
item = (url, method, func)
cls._docoratedRouteHandlers.append(item)
return func
return route_decorator
# ----------------------------------------------------------------------------
@staticmethod
def HTMLEscape(s) :
return ''.join(MicroWebSrv._html_escape_chars.get(c, c) for c in s)
# ----------------------------------------------------------------------------
@staticmethod
def _startThread(func, args=()) :
try :
start_new_thread(func, args)
except :
global _mwsrv_thread_id
try :
_mwsrv_thread_id += 1
except :
_mwsrv_thread_id = 0
try :
start_new_thread('MWSRV_THREAD_%s' % _mwsrv_thread_id, func, args)
except :
return False
return True
# ----------------------------------------------------------------------------
@staticmethod
def _unquote(s) :
r = str(s).split('%')
try :
b = r[0].encode()
for i in range(1, len(r)) :
try :
b += bytes([int(r[i][:2], 16)]) + r[i][2:].encode()
except :
b += b'%' + r[i].encode()
return b.decode('UTF-8')
except :
return str(s)
# ------------------------------------------------------------------------------
@staticmethod
def _unquote_plus(s) :
return MicroWebSrv._unquote(s.replace('+', ' '))
# ------------------------------------------------------------------------------
@staticmethod
def _fileExists(path) :
try :
stat(path)
return True
except :
return False
# ----------------------------------------------------------------------------
@staticmethod
def _isPyHTMLFile(filename) :
return filename.lower().endswith(MicroWebSrv._pyhtmlPagesExt)
# ============================================================================
# ===( Constructor )==========================================================
# ============================================================================
def __init__( self,
routeHandlers = [],
port = 80,
bindIP = '0.0.0.0',
webPath = "/flash/www" ) :
self._srvAddr = (bindIP, port)
self._webPath = webPath
self._notFoundUrl = None
self._started = False
self.MaxWebSocketRecvLen = 1024
self.WebSocketThreaded = True
self.AcceptWebSocketCallback = None
self.LetCacheStaticContentLevel = 2
self._routeHandlers = []
routeHandlers += self._docoratedRouteHandlers
for route, method, func in routeHandlers :
routeParts = route.split('/')
# -> ['', 'users', '<uID>', 'addresses', '<addrID>', 'test', '<anotherID>']
routeArgNames = []
routeRegex = ''
for s in routeParts :
if s.startswith('<') and s.endswith('>') :
routeArgNames.append(s[1:-1])
routeRegex += '/(\\w*)'
elif s :
routeRegex += '/' + s
routeRegex += '$'
# -> '/users/(\w*)/addresses/(\w*)/test/(\w*)$'
routeRegex = re.compile(routeRegex)
self._routeHandlers.append(MicroWebSrvRoute(route, method, func, routeArgNames, routeRegex))
# ============================================================================
# ===( Server Process )=======================================================
# ============================================================================
def _serverProcess(self) :
self._started = True
while True :
try :
client, cliAddr = self._server.accept()
except Exception as ex :
if ex.args and ex.args[0] == 113 :
break
continue
self._client(self, client, cliAddr)
self._started = False
# ============================================================================
# ===( Functions )============================================================
# ============================================================================
def Start(self, threaded=False) :
if not self._started :
self._server = socket.socket()
self._server.setsockopt( socket.SOL_SOCKET,
socket.SO_REUSEADDR,
1 )
self._server.bind(self._srvAddr)
self._server.listen(16)
if threaded :
MicroWebSrv._startThread(self._serverProcess)
else :
self._serverProcess()
# ----------------------------------------------------------------------------
def Stop(self) :
if self._started :
self._server.close()
# ----------------------------------------------------------------------------
def IsStarted(self) :
return self._started
# ----------------------------------------------------------------------------
def SetNotFoundPageUrl(self, url=None) :
self._notFoundUrl = url
# ----------------------------------------------------------------------------
def GetMimeTypeFromFilename(self, filename) :
filename = filename.lower()
for ext in self._mimeTypes :
if filename.endswith(ext) :
return self._mimeTypes[ext]
return None
# ----------------------------------------------------------------------------
def GetRouteHandler(self, resUrl, method) :
if self._routeHandlers :
#resUrl = resUrl.upper()
if resUrl.endswith('/') :
resUrl = resUrl[:-1]
method = method.upper()
for rh in self._routeHandlers :
if rh.method == method :
m = rh.routeRegex.match(resUrl)
if m : # found matching route?
if rh.routeArgNames :
routeArgs = {}
for i, name in enumerate(rh.routeArgNames) :
value = m.group(i+1)
try :
value = int(value)
except :
pass
routeArgs[name] = value
return (rh.func, routeArgs)
else :
return (rh.func, None)
return (None, None)
# ----------------------------------------------------------------------------
def _physPathFromURLPath(self, urlPath) :
if urlPath == '/' :
for idxPage in self._indexPages :
physPath = self._webPath + '/' + idxPage
if MicroWebSrv._fileExists(physPath) :
return physPath
else :
physPath = self._webPath + urlPath.replace('../', '/')
if MicroWebSrv._fileExists(physPath) :
return physPath
return None
# ============================================================================
# ===( Class Client )========================================================
# ============================================================================
class _client :
# ------------------------------------------------------------------------
def __init__(self, microWebSrv, socket, addr) :
socket.settimeout(2)
self._microWebSrv = microWebSrv
self._socket = socket
self._addr = addr
self._method = None
self._path = None
self._httpVer = None
self._resPath = "/"
self._queryString = ""
self._queryParams = { }
self._headers = { }
self._contentType = None
self._contentLength = 0
if hasattr(socket, 'readline'): # MicroPython
self._socketfile = self._socket
else: # CPython
self._socketfile = self._socket.makefile('rwb')
self._processRequest()
# ------------------------------------------------------------------------
def _processRequest(self) :
try :
response = MicroWebSrv._response(self)
if self._parseFirstLine(response) :
if self._parseHeader(response) :
upg = self._getConnUpgrade()
if not upg :
routeHandler, routeArgs = self._microWebSrv.GetRouteHandler(self._resPath, self._method)
if routeHandler :
try :
if routeArgs is not None:
routeHandler(self, response, routeArgs)
else :
routeHandler(self, response)
except Exception as ex :
print('MicroWebSrv handler exception:\r\n - In route %s %s\r\n - %s' % (self._method, self._resPath, ex))
raise ex
elif self._method.upper() == "GET" :
filepath = self._microWebSrv._physPathFromURLPath(self._resPath)
if filepath :
if MicroWebSrv._isPyHTMLFile(filepath) :
response.WriteResponsePyHTMLFile(filepath)
else :
contentType = self._microWebSrv.GetMimeTypeFromFilename(filepath)
if contentType :
if self._microWebSrv.LetCacheStaticContentLevel > 0 :
if self._microWebSrv.LetCacheStaticContentLevel > 1 and \
'if-modified-since' in self._headers :
response.WriteResponseNotModified()
else:
headers = { 'Last-Modified' : 'Fri, 1 Jan 2018 23:42:00 GMT', \
'Cache-Control' : 'max-age=315360000' }
response.WriteResponseFile(filepath, contentType, headers)
else :
response.WriteResponseFile(filepath, contentType)
else :
response.WriteResponseForbidden()
else :
response.WriteResponseNotFound()
else :
response.WriteResponseMethodNotAllowed()
elif upg == 'websocket' and 'MicroWebSocket' in globals() \
and self._microWebSrv.AcceptWebSocketCallback :
MicroWebSocket( socket = self._socket,
httpClient = self,
httpResponse = response,
maxRecvLen = self._microWebSrv.MaxWebSocketRecvLen,
threaded = self._microWebSrv.WebSocketThreaded,
acceptCallback = self._microWebSrv.AcceptWebSocketCallback )
return
else :
response.WriteResponseNotImplemented()
else :
response.WriteResponseBadRequest()
except :
response.WriteResponseInternalServerError()
try :
if self._socketfile is not self._socket:
self._socketfile.close()
self._socket.close()
except :
pass
# ------------------------------------------------------------------------
def _parseFirstLine(self, response) :
try :
elements = self._socketfile.readline().decode().strip().split()
if len(elements) == 3 :
self._method = elements[0].upper()
self._path = elements[1]
self._httpVer = elements[2].upper()
elements = self._path.split('?', 1)
if len(elements) > 0 :
self._resPath = MicroWebSrv._unquote_plus(elements[0])
if len(elements) > 1 :
self._queryString = elements[1]
elements = self._queryString.split('&')
for s in elements :
param = s.split('=', 1)
if len(param) > 0 :
value = MicroWebSrv._unquote(param[1]) if len(param) > 1 else ''
self._queryParams[MicroWebSrv._unquote(param[0])] = value
return True
except :
pass
return False
# ------------------------------------------------------------------------
def _parseHeader(self, response) :
while True :
elements = self._socketfile.readline().decode().strip().split(':', 1)
if len(elements) == 2 :
self._headers[elements[0].strip().lower()] = elements[1].strip()
elif len(elements) == 1 and len(elements[0]) == 0 :
if self._method == 'POST' or self._method == 'PUT' :
self._contentType = self._headers.get("content-type", None)
self._contentLength = int(self._headers.get("content-length", 0))
return True
else :
return False
# ------------------------------------------------------------------------
def _getConnUpgrade(self) :
if 'upgrade' in self._headers.get('connection', '').lower() :
return self._headers.get('upgrade', '').lower()
return None
# ------------------------------------------------------------------------
def GetServer(self) :
return self._microWebSrv
# ------------------------------------------------------------------------
def GetAddr(self) :
return self._addr
# ------------------------------------------------------------------------
def GetIPAddr(self) :
return self._addr[0]
# ------------------------------------------------------------------------
def GetPort(self) :
return self._addr[1]
# ------------------------------------------------------------------------
def GetRequestMethod(self) :
return self._method
# ------------------------------------------------------------------------
def GetRequestTotalPath(self) :
return self._path
# ------------------------------------------------------------------------
def GetRequestPath(self) :
return self._resPath
# ------------------------------------------------------------------------
def GetRequestQueryString(self) :
return self._queryString
# ------------------------------------------------------------------------
def GetRequestQueryParams(self) :
return self._queryParams
# ------------------------------------------------------------------------
def GetRequestHeaders(self) :
return self._headers
# ------------------------------------------------------------------------
def GetRequestContentType(self) :
return self._contentType
# ------------------------------------------------------------------------
def GetRequestContentLength(self) :
return self._contentLength
# ------------------------------------------------------------------------
def ReadRequestContent(self, size=None) :
if size is None :
size = self._contentLength
if size > 0 :
try :
return self._socketfile.read(size)
except :
pass
return b''
# ------------------------------------------------------------------------
def ReadRequestPostedFormData(self) :
res = { }
data = self.ReadRequestContent()
if data :
elements = data.decode().split('&')
for s in elements :
param = s.split('=', 1)
if len(param) > 0 :
value = MicroWebSrv._unquote_plus(param[1]) if len(param) > 1 else ''
res[MicroWebSrv._unquote_plus(param[0])] = value
return res
# ------------------------------------------------------------------------
def ReadRequestContentAsJSON(self) :
data = self.ReadRequestContent()
if data :
try :
return loads(data.decode())
except :
pass
return None
# ============================================================================
# ===( Class Response )======================================================
# ============================================================================
class _response :
# ------------------------------------------------------------------------
def __init__(self, client) :
self._client = client
# ------------------------------------------------------------------------
def _write(self, data, strEncoding='ISO-8859-1') :
if data :
if type(data) == str :
data = data.encode(strEncoding)
data = memoryview(data)
while data :
n = self._client._socketfile.write(data)
if n is None :
return False
data = data[n:]
return True
return False
# ------------------------------------------------------------------------
def _writeFirstLine(self, code) :
reason = self._responseCodes.get(code, ('Unknown reason', ))[0]
return self._write("HTTP/1.1 %s %s\r\n" % (code, reason))
# ------------------------------------------------------------------------
def _writeHeader(self, name, value) :
return self._write("%s: %s\r\n" % (name, value))
# ------------------------------------------------------------------------
def _writeContentTypeHeader(self, contentType, charset=None) :
if contentType :
ct = contentType \
+ (("; charset=%s" % charset) if charset else "")
else :
ct = "application/octet-stream"
self._writeHeader("Content-Type", ct)
# ------------------------------------------------------------------------
def _writeServerHeader(self) :
self._writeHeader("Server", "MicroWebSrv by JC`zic")
# ------------------------------------------------------------------------
def _writeEndHeader(self) :
return self._write("\r\n")
# ------------------------------------------------------------------------
def _writeBeforeContent(self, code, headers, contentType, contentCharset, contentLength) :
self._writeFirstLine(code)
if isinstance(headers, dict) :
for header in headers :
self._writeHeader(header, headers[header])
if contentLength > 0 :
self._writeContentTypeHeader(contentType, contentCharset)
self._writeHeader("Content-Length", contentLength)
self._writeServerHeader()
self._writeHeader("Connection", "close")
self._writeEndHeader()
# ------------------------------------------------------------------------
def WriteSwitchProto(self, upgrade, headers=None) :
self._writeFirstLine(101)
self._writeHeader("Connection", "Upgrade")
self._writeHeader("Upgrade", upgrade)
if isinstance(headers, dict) :
for header in headers :
self._writeHeader(header, headers[header])
self._writeServerHeader()
self._writeEndHeader()
if self._client._socketfile is not self._client._socket :
self._client._socketfile.flush() # CPython needs flush to continue protocol
# ------------------------------------------------------------------------
def WriteResponse(self, code, headers, contentType, contentCharset, content) :
try :
if content :
if type(content) == str :
content = content.encode(contentCharset)
contentLength = len(content)
else :
contentLength = 0
self._writeBeforeContent(code, headers, contentType, contentCharset, contentLength)
if content :
return self._write(content)
return True
except :
return False
# ------------------------------------------------------------------------
def WriteResponsePyHTMLFile(self, filepath, headers=None, vars=None) :
if 'MicroWebTemplate' in globals() :
with open(filepath, 'r') as file :
code = file.read()
mWebTmpl = MicroWebTemplate(code, escapeStrFunc=MicroWebSrv.HTMLEscape, filepath=filepath)
try :
tmplResult = mWebTmpl.Execute(None, vars)
return self.WriteResponse(200, headers, "text/html", "UTF-8", tmplResult)
except Exception as ex :
return self.WriteResponse( 500,
None,
"text/html",
"UTF-8",
self._execErrCtnTmpl % {
'module' : 'PyHTML',
'message' : str(ex)
} )
return self.WriteResponseNotImplemented()
# ------------------------------------------------------------------------
def WriteResponseFile(self, filepath, contentType=None, headers=None) :
try :
size = stat(filepath)[6]
if size > 0 :
with open(filepath, 'rb') as file :
self._writeBeforeContent(200, headers, contentType, None, size)
try :
buf = bytearray(1024)
while size > 0 :
x = file.readinto(buf)
if x < len(buf) :
buf = memoryview(buf)[:x]
if not self._write(buf) :
return False
size -= x
return True
except :
self.WriteResponseInternalServerError()
return False
except :
pass
self.WriteResponseNotFound()
return False
# ------------------------------------------------------------------------
def WriteResponseFileAttachment(self, filepath, attachmentName, headers=None) :
if not isinstance(headers, dict) :
headers = { }
headers["Content-Disposition"] = "attachment; filename=\"%s\"" % attachmentName
return self.WriteResponseFile(filepath, None, headers)
# ------------------------------------------------------------------------
def WriteResponseOk(self, headers=None, contentType=None, contentCharset=None, content=None) :
return self.WriteResponse(200, headers, contentType, contentCharset, content)
# ------------------------------------------------------------------------
def WriteResponseJSONOk(self, obj=None, headers=None) :
return self.WriteResponse(200, headers, "application/json", "UTF-8", dumps(obj))
# ------------------------------------------------------------------------
def WriteResponseRedirect(self, location) :
headers = { "Location" : location }
return self.WriteResponse(302, headers, None, None, None)
# ------------------------------------------------------------------------
def WriteResponseError(self, code) :
responseCode = self._responseCodes.get(code, ('Unknown reason', ''))
return self.WriteResponse( code,
None,
"text/html",
"UTF-8",
self._errCtnTmpl % {
'code' : code,
'reason' : responseCode[0],
'message' : responseCode[1]
} )
# ------------------------------------------------------------------------
def WriteResponseJSONError(self, code, obj=None) :
return self.WriteResponse( code,
None,
"application/json",
"UTF-8",
dumps(obj if obj else { }) )
# ------------------------------------------------------------------------
def WriteResponseNotModified(self) :
return self.WriteResponseError(304)
# ------------------------------------------------------------------------
def WriteResponseBadRequest(self) :
return self.WriteResponseError(400)
# ------------------------------------------------------------------------
def WriteResponseForbidden(self) :
return self.WriteResponseError(403)
# ------------------------------------------------------------------------
def WriteResponseNotFound(self) :
if self._client._microWebSrv._notFoundUrl :
self.WriteResponseRedirect(self._client._microWebSrv._notFoundUrl)
else :
return self.WriteResponseError(404)
# ------------------------------------------------------------------------
def WriteResponseMethodNotAllowed(self) :
return self.WriteResponseError(405)
# ------------------------------------------------------------------------
def WriteResponseInternalServerError(self) :
return self.WriteResponseError(500)
# ------------------------------------------------------------------------
def WriteResponseNotImplemented(self) :
return self.WriteResponseError(501)
# ------------------------------------------------------------------------
def FlashMessage(self, messageText, messageStyle='') :
if 'MicroWebTemplate' in globals() :
MicroWebTemplate.MESSAGE_TEXT = messageText
MicroWebTemplate.MESSAGE_STYLE = messageStyle
# ------------------------------------------------------------------------
_errCtnTmpl = """\
<html>
<head>
<title>Error</title>
</head>
<body>
<h1>%(code)d %(reason)s</h1>
%(message)s
</body>
</html>
"""
# ------------------------------------------------------------------------
_execErrCtnTmpl = """\
<html>
<head>
<title>Page execution error</title>
</head>
<body>
<h1>%(module)s page execution error</h1>
%(message)s
</body>
</html>
"""
# ------------------------------------------------------------------------
_responseCodes = {
100: ('Continue', 'Request received, please continue'),
101: ('Switching Protocols',
'Switching to new protocol; obey Upgrade header'),
200: ('OK', 'Request fulfilled, document follows'),
201: ('Created', 'Document created, URL follows'),
202: ('Accepted',
'Request accepted, processing continues off-line'),
203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
204: ('No Content', 'Request fulfilled, nothing follows'),
205: ('Reset Content', 'Clear input form for further input.'),
206: ('Partial Content', 'Partial content follows.'),
300: ('Multiple Choices',
'Object has several resources -- see URI list'),
301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
302: ('Found', 'Object moved temporarily -- see URI list'),
303: ('See Other', 'Object moved -- see Method and URL list'),
304: ('Not Modified',
'Document has not changed since given time'),
305: ('Use Proxy',
'You must use proxy specified in Location to access this '
'resource.'),
307: ('Temporary Redirect',
'Object moved temporarily -- see URI list'),
400: ('Bad Request',
'Bad request syntax or unsupported method'),
401: ('Unauthorized',
'No permission -- see authorization schemes'),
402: ('Payment Required',
'No payment -- see charging schemes'),
403: ('Forbidden',
'Request forbidden -- authorization will not help'),
404: ('Not Found', 'Nothing matches the given URI'),
405: ('Method Not Allowed',
'Specified method is invalid for this resource.'),
406: ('Not Acceptable', 'URI not available in preferred format.'),
407: ('Proxy Authentication Required', 'You must authenticate with '
'this proxy before proceeding.'),
408: ('Request Timeout', 'Request timed out; try again later.'),
409: ('Conflict', 'Request conflict.'),
410: ('Gone',
'URI no longer exists and has been permanently removed.'),
411: ('Length Required', 'Client must specify Content-Length.'),
412: ('Precondition Failed', 'Precondition in headers is false.'),
413: ('Request Entity Too Large', 'Entity is too large.'),
414: ('Request-URI Too Long', 'URI is too long.'),
415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
416: ('Requested Range Not Satisfiable',
'Cannot satisfy request range.'),
417: ('Expectation Failed',
'Expect condition could not be satisfied.'),
500: ('Internal Server Error', 'Server got itself in trouble'),
501: ('Not Implemented',
'Server does not support this operation'),
502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
503: ('Service Unavailable',
'The server cannot process the request due to a high load'),
504: ('Gateway Timeout',
'The gateway server did not receive a timely response'),
505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
}
# ============================================================================
# ============================================================================
# ============================================================================
Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

+336
View File
@@ -0,0 +1,336 @@
"""
The MIT License (MIT)
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
import re
class MicroWebTemplate :
# ============================================================================
# ===( Constants )============================================================
# ============================================================================
TOKEN_OPEN = '{{'
TOKEN_CLOSE = '}}'
TOKEN_OPEN_LEN = len(TOKEN_OPEN)
TOKEN_CLOSE_LEN = len(TOKEN_CLOSE)
INSTRUCTION_PYTHON = 'py'
INSTRUCTION_IF = 'if'
INSTRUCTION_ELIF = 'elif'
INSTRUCTION_ELSE = 'else'
INSTRUCTION_FOR = 'for'
INSTRUCTION_END = 'end'
INSTRUCTION_INCLUDE = 'include'
MESSAGE_TEXT = ''
MESSAGE_STYLE = ''
# ============================================================================
# ===( Constructor )==========================================================
# ============================================================================
def __init__(self, code, escapeStrFunc=None, filepath='') :
self._code = code
self._escapeStrFunc = escapeStrFunc
self._filepath = filepath
self._pos = 0
self._endPos = len(code)-1
self._line = 1
self._reIdentifier = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$')
self._pyGlobalVars = { }
self._pyLocalVars = { }
self._rendered = ''
self._instructions = {
MicroWebTemplate.INSTRUCTION_PYTHON : self._processInstructionPYTHON,
MicroWebTemplate.INSTRUCTION_IF : self._processInstructionIF,
MicroWebTemplate.INSTRUCTION_ELIF : self._processInstructionELIF,
MicroWebTemplate.INSTRUCTION_ELSE : self._processInstructionELSE,
MicroWebTemplate.INSTRUCTION_FOR : self._processInstructionFOR,
MicroWebTemplate.INSTRUCTION_END : self._processInstructionEND,
MicroWebTemplate.INSTRUCTION_INCLUDE: self._processInstructionINCLUDE,
}
# ============================================================================
# ===( Functions )============================================================
# ============================================================================
def Validate(self, pyGlobalVars=None, pyLocalVars=None) :
try :
self._parseCode(pyGlobalVars, pyLocalVars, execute=False)
return None
except Exception as ex :
return str(ex)
# ----------------------------------------------------------------------------
def Execute(self, pyGlobalVars=None, pyLocalVars=None) :
try :
self._parseCode(pyGlobalVars, pyLocalVars, execute=True)
return self._rendered
except Exception as ex :
raise Exception(str(ex))
# ============================================================================
# ===( Utils )===============================================================
# ============================================================================
def _parseCode(self, pyGlobalVars, pyLocalVars, execute) :
if pyGlobalVars:
self._pyGlobalVars.update(pyGlobalVars)
if pyLocalVars:
self._pyLocalVars.update(pyLocalVars)
self._pyLocalVars['MESSAGE_TEXT'] = MicroWebTemplate.MESSAGE_TEXT
self._pyLocalVars['MESSAGE_STYLE'] = MicroWebTemplate.MESSAGE_STYLE
self._rendered = ''
newTokenToProcess = self._parseBloc(execute)
if newTokenToProcess is not None :
raise Exception( '"%s" instruction is not valid here (line %s)'
% (newTokenToProcess, self._line) )
MicroWebTemplate.MESSAGE_TEXT = ''
MicroWebTemplate.MESSAGE_STYLE = ''
# ----------------------------------------------------------------------------
def _parseBloc(self, execute) :
while self._pos <= self._endPos :
c = self._code[self._pos]
if c == MicroWebTemplate.TOKEN_OPEN[0] and \
self._code[ self._pos : self._pos + MicroWebTemplate.TOKEN_OPEN_LEN ] == MicroWebTemplate.TOKEN_OPEN :
self._pos += MicroWebTemplate.TOKEN_OPEN_LEN
tokenContent = ''
x = self._pos
while True :
if x > self._endPos :
raise Exception("%s is missing (line %s)" % (MicroWebTemplate.TOKEN_CLOSE, self._line))
c = self._code[x]
if c == MicroWebTemplate.TOKEN_CLOSE[0] and \
self._code[ x : x + MicroWebTemplate.TOKEN_CLOSE_LEN ] == MicroWebTemplate.TOKEN_CLOSE :
self._pos = x + MicroWebTemplate.TOKEN_CLOSE_LEN
break
elif c == '\n' :
self._line += 1
tokenContent += c
x += 1
newTokenToProcess = self._processToken(tokenContent, execute)
if newTokenToProcess is not None :
return newTokenToProcess
continue
elif c == '\n' :
self._line += 1
if execute :
self._rendered += c
self._pos += 1
return None
# ----------------------------------------------------------------------------
def _processToken(self, tokenContent, execute) :
tokenContent = tokenContent.strip()
parts = tokenContent.split(' ', 1)
instructName = parts[0].strip()
instructBody = parts[1].strip() if len(parts) > 1 else None
if len(instructName) == 0 :
raise Exception( '"%s %s" : instruction is missing (line %s)'
% (MicroWebTemplate.TOKEN_OPEN, MicroWebTemplate.TOKEN_CLOSE, self._line) )
newTokenToProcess = None
if instructName in self._instructions :
newTokenToProcess = self._instructions[instructName](instructBody, execute)
elif execute :
try :
s = str( eval( tokenContent,
self._pyGlobalVars,
self._pyLocalVars ) )
if (self._escapeStrFunc is not None) :
self._rendered += self._escapeStrFunc(s)
else :
self._rendered += s
except Exception as ex :
raise Exception('%s (line %s)' % (str(ex), self._line))
return newTokenToProcess
# ----------------------------------------------------------------------------
def _processInstructionPYTHON(self, instructionBody, execute) :
if instructionBody is not None :
raise Exception( 'Instruction "%s" is invalid (line %s)'
% (MicroWebTemplate.INSTRUCTION_PYTHON, self._line) )
pyCode = ''
while True :
if self._pos > self._endPos :
raise Exception( '"%s" instruction is missing (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
c = self._code[self._pos]
if c == MicroWebTemplate.TOKEN_OPEN[0] and \
self._code[ self._pos : self._pos + MicroWebTemplate.TOKEN_OPEN_LEN ] == MicroWebTemplate.TOKEN_OPEN :
self._pos += MicroWebTemplate.TOKEN_OPEN_LEN
tokenContent = ''
x = self._pos
while True :
if x > self._endPos :
raise Exception("%s is missing (line %s)" % (MicroWebTemplate.TOKEN_CLOSE, self._line))
c = self._code[x]
if c == MicroWebTemplate.TOKEN_CLOSE[0] and \
self._code[ x : x + MicroWebTemplate.TOKEN_CLOSE_LEN ] == MicroWebTemplate.TOKEN_CLOSE :
self._pos = x + MicroWebTemplate.TOKEN_CLOSE_LEN
break
elif c == '\n' :
self._line += 1
tokenContent += c
x += 1
tokenContent = tokenContent.strip()
if tokenContent == MicroWebTemplate.INSTRUCTION_END :
break
raise Exception( '"%s" is a bad instruction in a python bloc (line %s)'
% (tokenContent, self._line) )
elif c == '\n' :
self._line += 1
if execute :
pyCode += c
self._pos += 1
if execute :
lines = pyCode.split('\n')
indent = ''
for line in lines :
if len(line.strip()) > 0 :
for c in line :
if c == ' ' or c == '\t' :
indent += c
else :
break
break
pyCode = ''
for line in lines :
if line.find(indent) == 0 :
line = line[len(indent):]
pyCode += line + '\n'
try :
exec(pyCode, self._pyGlobalVars, self._pyLocalVars)
except Exception as ex :
raise Exception('%s (line %s)' % (str(ex), self._line))
return None
# ----------------------------------------------------------------------------
def _processInstructionIF(self, instructionBody, execute) :
if instructionBody is not None :
if execute :
try :
if (' ' not in instructionBody) and \
('=' not in instructionBody) and \
('<' not in instructionBody) and \
('>' not in instructionBody) and \
(instructionBody not in self._pyGlobalVars) and \
(instructionBody not in self._pyLocalVars):
result = False
else:
result = bool(eval(instructionBody, self._pyGlobalVars, self._pyLocalVars))
except Exception as ex :
raise Exception('%s (line %s)' % (str(ex), self._line))
else :
result = False
newTokenToProcess = self._parseBloc(execute and result)
if newTokenToProcess is not None :
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
return None
elif newTokenToProcess == MicroWebTemplate.INSTRUCTION_ELSE :
newTokenToProcess = self._parseBloc(execute and not result)
if newTokenToProcess is not None :
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
return None
raise Exception( '"%s" instruction waited (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s" instruction is missing (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
elif newTokenToProcess == MicroWebTemplate.INSTRUCTION_ELIF :
self._processInstructionIF(self._elifInstructionBody, execute and not result)
return None
raise Exception( '"%s" instruction waited (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s" instruction is missing (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
% (MicroWebTemplate.INSTRUCTION_IF, self._line) )
# ----------------------------------------------------------------------------
def _processInstructionELIF(self, instructionBody, execute) :
if instructionBody is None :
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
% (MicroWebTemplate.INSTRUCTION_ELIF, self._line) )
self._elifInstructionBody = instructionBody
return MicroWebTemplate.INSTRUCTION_ELIF
# ----------------------------------------------------------------------------
def _processInstructionELSE(self, instructionBody, execute) :
if instructionBody is not None :
raise Exception( 'Instruction "%s" is invalid (line %s)'
% (MicroWebTemplate.INSTRUCTION_ELSE, self._line) )
return MicroWebTemplate.INSTRUCTION_ELSE
# ----------------------------------------------------------------------------
def _processInstructionFOR(self, instructionBody, execute) :
if instructionBody is not None :
parts = instructionBody.split(' ', 1)
identifier = parts[0].strip()
if self._reIdentifier.match(identifier) is not None and len(parts) > 1 :
parts = parts[1].strip().split(' ', 1)
if parts[0] == 'in' and len(parts) > 1 :
expression = parts[1].strip()
newTokenToProcess = None
beforePos = self._pos
if execute :
try :
result = eval(expression, self._pyGlobalVars, self._pyLocalVars)
except :
raise Exception('%s (line %s)' % (str(expression), self._line))
if execute and len(result) > 0 :
for x in result :
self._pyLocalVars[identifier] = x
self._pos = beforePos
newTokenToProcess = self._parseBloc(True)
if newTokenToProcess != MicroWebTemplate.INSTRUCTION_END :
break
else :
newTokenToProcess = self._parseBloc(False)
if newTokenToProcess is not None :
if newTokenToProcess == MicroWebTemplate.INSTRUCTION_END :
return None
raise Exception( '"%s" instruction waited (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s" instruction is missing (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
raise Exception( '"%s %s" is an invalid syntax'
% (MicroWebTemplate.INSTRUCTION_FOR, instructionBody) )
raise Exception( '"%s" alone is an incomplete syntax (line %s)'
% (MicroWebTemplate.INSTRUCTION_FOR, self._line) )
# ----------------------------------------------------------------------------
def _processInstructionEND(self, instructionBody, execute) :
if instructionBody is not None :
raise Exception( 'Instruction "%s" is invalid (line %s)'
% (MicroWebTemplate.INSTRUCTION_END, self._line) )
return MicroWebTemplate.INSTRUCTION_END
# ----------------------------------------------------------------------------
def _processInstructionINCLUDE(self, instructionBody, execute) :
if not instructionBody :
raise Exception( '"%s" alone is an incomplete syntax (line %s)' % (MicroWebTemplate.INSTRUCTION_INCLUDE, self._line) )
filename = instructionBody.replace('"','').replace("'",'').strip()
idx = self._filepath.rindex('/')
if idx >= 0 :
filename = self._filepath[:idx+1] + filename
with open(filename, 'r') as file :
includeCode = file.read()
self._code = self._code[:self._pos] + includeCode + self._code[self._pos:]
self._endPos += len(includeCode)
# ============================================================================
# ============================================================================
# ============================================================================
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

+28
View File
@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang=fr>
<head>
<meta charset="UTF-8" />
<title>Page de test MicroWebSrv</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Page de test MicroWebSrv</h1>
<h2>Hello !</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget ligula quis libero mollis dapibus. Suspendisse potenti. Nullam facilisis neque et sem. Proin placerat adipiscing urna. Aenean sollicitudin. Mauris lorem erat, fringilla quis, sagittis a, varius sed, nunc. Pellentesque ligula. Nullam egestas eleifend turpis. Vivamus ac sapien. Sed venenatis, ligula ut scelerisque vehicula, erat tellus euismod ipsum, eget faucibus tortor arcu et lectus. Vivamus vel purus. Fusce dignissim tortor quis diam elementum fermentum. Mauris eleifend lorem vel arcu. Vivamus tempus faucibus lectus. Curabitur volutpat ornare mi. Curabitur ac libero. Sed eu elit ac metus egestas iaculis.
</p>
<br />
<hr />
<br />
<div style="text-align: center">
<img src="pdf.png" />
<p>
Afficher « <a href="test.pdf">un fichier PDF</a> »
</p>
</div>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

+36
View File
@@ -0,0 +1,36 @@
html, body {
margin: 0;
padding: 0;
}
body {
background-color: white;
font-family: Verdana, sans-serif;
font-size: 100%;
}
h1 {
font-size: 200%;
color: navy;
text-align: center;
}
h2 {
font-size: 150%;
color: red;
padding-left: 15px;
}
p,ul,li,td {
color: black;
}
a:link {
color: green;
text-decoration: underline;
}
a:visited {
color: gray;
}
a:hover {
color: red;
text-decoration: none;
}
a:active, a:focus {
color: red;
}
Binary file not shown.
+34
View File
@@ -0,0 +1,34 @@
<html>
<head>
<title>TEST</title>
</head>
<body>
<h1>BEGIN</h1>
{{ py }}
def _testFunction(x) :
return "IN TEST FUNCTION %s" % x
{{ end }}
<div style="background-color: black; color: white;">
{{ for toto in range(3) }}
This is an HTML test...<br />
TOTO = {{ toto + 1 }} !<br />
{{ for toto2 in range(3) }}
TOTO2 = {{ _testFunction(toto2) }}
{{ end }}
Ok good.<br />
{{ end }}
</div>
{{ _testFunction(100) }}<br />
<br />
{{ if 2+5 < 3 }}
IN IF (1)
{{ elif 10+15 != 25 }}
IN ELIF (2)
{{ elif 10+15 == 25 }}
IN ELIF (3)
{{ else }}
IN ELSE (4)
{{ end }}
<h1>JC :')</h1>
</body>
</html>
+78
View File
@@ -0,0 +1,78 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>MicroWebSocket Test</title>
</head>
<script language="javascript">
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket()
{
var wsUri = "ws://" + window.location.hostname;
writeToScreen("Connection to " + wsUri + "...")
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen (evt) };
websocket.onclose = function(evt) { onClose (evt) };
websocket.onmessage = function(evt) { onMessage (evt) };
websocket.onerror = function(evt) { onError (evt) };
}
function onOpen(evt)
{
writeToScreen("<strong>-- CONNECTED --</strong>");
SendMsg("Hello world :)");
SendMsg("This is a WebSocket test");
SendMsg("(with a text frame encoded in UTF-8)");
setTimeout( function() { websocket.close() }, 500 )
}
function onClose(evt)
{
writeToScreen("<strong>-- DISCONNECTED --</strong>");
}
function onMessage(evt)
{
writeToScreen('MSG FROM SERVER : <span style="color: blue;">' + evt.data + '</span>');
}
function onError(evt)
{
writeToScreen('ERROR : <span style="color: red;">' + evt.data + '</span>');
}
function SendMsg(msg)
{
writeToScreen('MSG TO SERVER : <span style="color: green;">' + msg + '</span>');
websocket.send(msg);
}
function writeToScreen(s)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = s;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<body>
<h2>MicroWebSocket Test :</h2>
<div id="output"></div>
</body>
</html>
+6
View File
@@ -0,0 +1,6 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*.egg-info
/dist
/.venv*
+8
View File
@@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (https://www.hc2.fr)
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.
@@ -0,0 +1,18 @@
"""
The MIT License (MIT)
Copyright © 2024 Jean-Christophe Bos (jczic.bos@gmail.com)
"""
print()
print(' -------------------------')
print(' - Python MicroWebSrv2 -')
print(' - version 2.1.0 -')
print(' - by JC`zic -')
print(' -------------------------')
print()
from .libs.XAsyncSockets import *
from .libs.urlUtils import *
from .webRoute import *
from .microWebSrv2 import *
@@ -0,0 +1,416 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from . import *
from .httpResponse import HttpResponse
from binascii import a2b_base64
import json
# ============================================================================
# ===( HttpRequest )==========================================================
# ============================================================================
class HttpRequest :
MAX_RECV_HEADER_LINES = 100
# ------------------------------------------------------------------------
def __init__(self, microWebSrv2, xasCli) :
self._mws2 = microWebSrv2
self._xasCli = xasCli
self._waitForRecvRequest()
# ------------------------------------------------------------------------
def _recvLine(self, onRecv) :
self._xasCli.AsyncRecvLine(onLineRecv=onRecv, timeoutSec=self._mws2._timeoutSec)
# ------------------------------------------------------------------------
def _waitForRecvRequest(self) :
self._httpVer = ''
self._method = ''
self._path = ''
self._headers = { }
self._content = None
self._response = HttpResponse(self._mws2, self)
self._recvLine(self._onFirstLineRecv)
# ------------------------------------------------------------------------
def _onFirstLineRecv(self, xasCli, line, arg) :
try :
elements = line.strip().split()
if len(elements) == 3 :
self._httpVer = elements[2].upper()
self._method = elements[0].upper()
elements = elements[1].split('?', 1)
self._path = UrlUtils.UnquotePlus(elements[0])
self._queryString = (elements[1] if len(elements) > 1 else '')
self._queryParams = { }
if self._queryString :
elements = self._queryString.split('&')
for s in elements :
p = s.split('=', 1)
if len(p) > 0 :
v = (UrlUtils.Unquote(p[1]) if len(p) > 1 else '')
self._queryParams[UrlUtils.Unquote(p[0])] = v
self._recvLine(self._onHeaderLineRecv)
else :
self._response.ReturnBadRequest()
except :
self._response.ReturnBadRequest()
# ------------------------------------------------------------------------
def _onHeaderLineRecv(self, xasCli, line, arg) :
try :
elements = line.strip().split(':', 1)
if len(elements) == 2 :
if len(self._headers) < HttpRequest.MAX_RECV_HEADER_LINES :
self._headers[elements[0].strip().lower()] = elements[1].strip()
self._recvLine(self._onHeaderLineRecv)
else :
self._response.ReturnEntityTooLarge()
elif len(elements) == 1 and len(elements[0]) == 0 :
self._processRequest()
else :
self._response.ReturnBadRequest()
except :
self._response.ReturnBadRequest()
# ------------------------------------------------------------------------
def _processRequest(self) :
if not self._processRequestModules() :
if not self.IsUpgrade :
if not self._processRequestRoutes() :
if self._method in ('GET', 'HEAD') :
filename = self._mws2.ResolvePhysicalPath(self._path)
if filename :
ct = self._mws2.GetMimeTypeFromFilename(filename)
if ct :
self._response.AllowCaching = True
self._response.ContentType = ct
self._response.ReturnFile(filename)
else :
self._response.ReturnForbidden()
else :
self._response.ReturnNotFound()
elif self._method == 'OPTIONS' :
if self._mws2.CORSAllowAll :
self._response.SetHeader( 'Access-Control-Allow-Methods', '*' )
self._response.SetHeader( 'Access-Control-Allow-Headers', '*' )
self._response.SetHeader( 'Access-Control-Allow-Credentials', 'true' )
self._response.SetHeader( 'Access-Control-Max-Age', '86400' )
self._response.ReturnOk()
else :
self._response.ReturnMethodNotAllowed()
else :
self._response.ReturnNotImplemented()
# ------------------------------------------------------------------------
def _processRequestModules(self) :
for modName, modInstance in self._mws2._modules.items() :
try :
modInstance.OnRequest(self._mws2, self)
if self._response.HeadersSent :
return True
except Exception as ex :
self._mws2.Log( 'Exception in request handler of module "%s" (%s).'
% (modName, ex),
self._mws2.ERROR )
return False
# ------------------------------------------------------------------------
def _processRequestRoutes(self) :
self._routeResult = ResolveRoute(self._method, self._path)
if self._routeResult :
cntLen = self.ContentLength
if not cntLen :
self._routeRequest()
elif self._method != 'GET' and self._method != 'HEAD' :
if cntLen <= self._mws2._maxContentLen :
def onContentRecv(xasCli, content, arg) :
self._content = content
self._routeRequest()
self._content = None
try :
self._xasCli.AsyncRecvData( size = cntLen,
onDataRecv = onContentRecv,
timeoutSec = self._mws2._timeoutSec )
except :
self._mws2.Log( 'Not enough memory to read a content of %s bytes.' % cntLen,
self._mws2.ERROR )
self._response.ReturnServiceUnavailable()
else :
self._response.ReturnEntityTooLarge()
else :
self._response.ReturnBadRequest()
return True
return False
# ------------------------------------------------------------------------
def _routeRequest(self) :
try :
currentResp = self._response
if self._routeResult.Args :
self._routeResult.Handler(self._mws2, self, self._routeResult.Args)
else :
self._routeResult.Handler(self._mws2, self)
if not currentResp.HeadersSent :
self._mws2.Log( 'No response was sent from route %s.'
% self._routeResult,
self._mws2.WARNING )
currentResp.ReturnNotImplemented()
except Exception as ex :
self._mws2.Log( 'Exception raised from route %s: %s'
% (self._routeResult, ex),
self._mws2.ERROR )
currentResp.ReturnInternalServerError()
# ------------------------------------------------------------------------
def GetPostedURLEncodedForm(self) :
res = { }
if self.ContentType.lower() == 'application/x-www-form-urlencoded' :
try :
elements = bytes(self._content).decode('UTF-8').split('&')
for s in elements :
p = s.split('=', 1)
if len(p) > 0 :
v = (UrlUtils.UnquotePlus(p[1]) if len(p) > 1 else '')
res[UrlUtils.UnquotePlus(p[0])] = v
except :
pass
return res
# ------------------------------------------------------------------------
def GetPostedJSONObject(self) :
if self.ContentType.lower() == 'application/json' :
try :
s = bytes(self._content).decode('UTF-8')
return json.loads(s)
except :
pass
return None
# ------------------------------------------------------------------------
def GetHeader(self, name) :
if not isinstance(name, str) or len(name) == 0 :
raise ValueError('"name" must be a not empty string.')
return self._headers.get(name.lower(), '')
# ------------------------------------------------------------------------
def CheckBasicAuth(self, username, password) :
if not isinstance(username, str) :
raise ValueError('"username" must be a string.')
if not isinstance(password, str) :
raise ValueError('"password" must be a string.')
auth = self.Authorization
if auth :
try :
auth = auth.split()
if len(auth) == 2 and auth[0].lower() == 'basic' :
auth = a2b_base64(auth[1].encode()).decode()
auth = auth.split(':')
return ( auth[0].lower() == username.lower() and \
auth[1] == password )
except :
pass
return False
# ------------------------------------------------------------------------
def CheckBearerAuth(self, token) :
if not isinstance(token, str) :
raise ValueError('"token" must be a string.')
auth = self.Authorization
if auth :
try :
auth = auth.split()
return ( len(auth) == 2 and \
auth[0].lower() == 'bearer' and \
auth[1] == token )
except :
pass
return False
# ------------------------------------------------------------------------
@property
def UserAddress(self) :
return self._xasCli.CliAddr
# ------------------------------------------------------------------------
@property
def IsSSL(self) :
return self._xasCli.IsSSL
# ------------------------------------------------------------------------
@property
def HttpVer(self) :
return self._httpVer
# ------------------------------------------------------------------------
@property
def Method(self) :
return self._method
# ------------------------------------------------------------------------
@property
def Path(self) :
return self._path
# ------------------------------------------------------------------------
@property
def QueryString(self) :
return self._queryString
# ------------------------------------------------------------------------
@property
def QueryParams(self) :
return self._queryParams
# ------------------------------------------------------------------------
@property
def Host(self) :
return self._headers.get('host', '')
# ------------------------------------------------------------------------
@property
def Accept(self) :
s = self._headers.get('accept', None)
if s :
return [x.strip() for x in s.split(',')]
return [ ]
# ------------------------------------------------------------------------
@property
def AcceptEncodings(self) :
s = self._headers.get('accept-encoding', None)
if s :
return [x.strip() for x in s.split(',')]
return [ ]
# ------------------------------------------------------------------------
@property
def AcceptLanguages(self) :
s = self._headers.get('accept-language', None)
if s :
return [x.strip() for x in s.split(',')]
return [ ]
# ------------------------------------------------------------------------
@property
def Cookies(self) :
s = self._headers.get('cookie', None)
if s :
return [x.strip() for x in s.split(';')]
return [ ]
# ------------------------------------------------------------------------
@property
def CacheControl(self) :
return self._headers.get('cache-control', '')
# ------------------------------------------------------------------------
@property
def Referer(self) :
return self._headers.get('referer', '')
# ------------------------------------------------------------------------
@property
def ContentType(self) :
return self._headers.get('content-type', '').split(';', 1)[0].strip()
# ------------------------------------------------------------------------
@property
def ContentLength(self) :
try :
return int(self._headers.get('content-length', 0))
except :
return 0
# ------------------------------------------------------------------------
@property
def UserAgent(self) :
return self._headers.get('user-agent', '')
# ------------------------------------------------------------------------
@property
def Authorization(self) :
return self._headers.get('authorization', '')
# ------------------------------------------------------------------------
@property
def Origin(self) :
return self._headers.get('origin', '')
# ------------------------------------------------------------------------
@property
def IsKeepAlive(self) :
return ('keep-alive' in self._headers.get('connection', '').lower())
# ------------------------------------------------------------------------
@property
def IsUpgrade(self) :
return ('upgrade' in self._headers.get('connection', '').lower())
# ------------------------------------------------------------------------
@property
def Upgrade(self) :
return self._headers.get('upgrade', '')
# ------------------------------------------------------------------------
@property
def Content(self) :
return self._content
# ------------------------------------------------------------------------
@property
def Response(self) :
return self._response
# ------------------------------------------------------------------------
@property
def XAsyncTCPClient(self) :
return self._xasCli
# ============================================================================
# ============================================================================
# ============================================================================
@@ -0,0 +1,550 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from os import stat
import json
# ============================================================================
# ===( HttpResponse )=========================================================
# ============================================================================
class HttpResponse :
_RESPONSE_CODES = {
100: ( 'Continue',
'Request received, please continue.' ),
101: ( 'Switching Protocols',
'Switching to new protocol; obey Upgrade header.' ),
200: ( 'OK',
'Request fulfilled, document follows.' ),
201: ( 'Created',
'Document created, URL follows' ),
202: ( 'Accepted',
'Request accepted, processing continues off-line.' ),
203: ( 'Non-Authoritative Information',
'Request fulfilled from cache' ),
204: ( 'No Content',
'Request fulfilled, nothing follows.' ),
205: ( 'Reset Content',
'Clear input form for further input.' ),
206: ( 'Partial Content',
'Partial content follows.' ),
300: ( 'Multiple Choices',
'Object has several resources -- see URI list.' ),
301: ( 'Moved Permanently',
'Object moved permanently -- see URI list.' ),
302: ( 'Found',
'Object moved temporarily -- see URI list.' ),
303: ( 'See Other',
'Object moved -- see Method and URL list.' ),
304: ( 'Not Modified',
'Document has not changed since given time.' ),
305: ( 'Use Proxy',
'You must use proxy specified in Location to access this resource.' ),
307: ( 'Temporary Redirect',
'Object moved temporarily -- see URI list.' ),
400: ( 'Bad Request',
'Bad request syntax or unsupported method.' ),
401: ( 'Unauthorized',
'No permission -- see authorization schemes.' ),
402: ( 'Payment Required',
'No payment -- see charging schemes.' ),
403: ( 'Forbidden',
'Request forbidden -- authorization will not help.' ),
404: ( 'Not Found',
'Nothing matches the given URI.' ),
405: ( 'Method Not Allowed',
'Specified method is invalid for this resource.' ),
406: ( 'Not Acceptable',
'URI not available in preferred format.' ),
407: ( 'Proxy Authentication Required',
'You must authenticate with this proxy before proceeding.' ),
408: ( 'Request Timeout',
'Request timed out; try again later.' ),
409: ( 'Conflict',
'Request conflict.' ),
410: ( 'Gone',
'URI no longer exists and has been permanently removed.' ),
411: ( 'Length Required',
'Client must specify Content-Length.' ),
412: ( 'Precondition Failed',
'Precondition in headers is false.' ),
413: ( 'Request Entity Too Large',
'Entity is too large.' ),
414: ( 'Request-URI Too Long',
'URI is too long.' ),
415: ( 'Unsupported Media Type',
'Entity body in unsupported format.' ),
416: ( 'Requested Range Not Satisfiable',
'Cannot satisfy request range.' ),
417: ( 'Expectation Failed',
'Expect condition could not be satisfied.' ),
500: ( 'Internal Server Error',
'Server got itself in trouble.' ),
501: ( 'Not Implemented',
'Server does not support this operation.' ),
502: ( 'Bad Gateway',
'Invalid responses from another server/proxy.' ),
503: ( 'Service Unavailable',
'The server cannot process the request due to a high load.' ),
504: ( 'Gateway Timeout',
'The gateway server did not receive a timely response.' ),
505: ( 'HTTP Version Not Supported',
'Cannot fulfill request.' )
}
_CODE_CONTENT_TMPL = """\
<html>
<head>
<title>MicroWebSrv2</title>
</head>
<body style="font-family: Verdana; background-color: Black; color: White;">
<h2>MicroWebSrv2 - [%(code)d] %(reason)s</h2>
%(message)s
</body>
</html>
"""
# ------------------------------------------------------------------------
def __init__(self, microWebSrv2, request) :
self._mws2 = microWebSrv2
self._request = request
self._xasCli = request.XAsyncTCPClient
self._headers = { }
self._allowCaching = False
self._acAllowOrigin = None
self._contentType = None
self._contentCharset = None
self._contentLength = 0
self._stream = None
self._sendingBuf = None
self._hdrSent = False
self._onSent = None
# ------------------------------------------------------------------------
def SetHeader(self, name, value) :
if not isinstance(name, str) or len(name) == 0 :
raise ValueError('"name" must be a not empty string.')
if value is None :
raise ValueError('"value" cannot be None.')
self._headers[name] = str(value)
# ------------------------------------------------------------------------
def _onDataSent(self, xasCli, arg) :
if self._stream :
try :
n = self._stream.readinto(self._sendingBuf)
if n < len(self._sendingBuf) :
self._stream.close()
self._stream = None
self._sendingBuf = self._sendingBuf[:n]
except :
self._xasCli.Close()
self._mws2.Log( 'Stream cannot be read for request "%s".'
% self._request._path,
self._mws2.ERROR )
return
if self._sendingBuf :
if self._contentLength :
self._xasCli.AsyncSendSendingBuffer( size = len(self._sendingBuf),
onDataSent = self._onDataSent )
if not self._stream :
self._sendingBuf = None
else :
def onChunkHdrSent(xasCli, arg) :
def onChunkDataSent(xasCli, arg) :
def onLastChunkSent(xasCli, arg) :
self._xasCli.AsyncSendData(b'0\r\n\r\n', onDataSent=self._onDataSent)
if self._stream :
onDataSent = self._onDataSent
else :
self._sendingBuf = None
onDataSent = onLastChunkSent
self._xasCli.AsyncSendData(b'\r\n', onDataSent=onDataSent)
self._xasCli.AsyncSendSendingBuffer( size = len(self._sendingBuf),
onDataSent = onChunkDataSent )
data = ('%x\r\n' % len(self._sendingBuf)).encode()
self._xasCli.AsyncSendData(data, onDataSent=onChunkHdrSent)
else :
self._xasCli.OnClosed = None
if self._keepAlive :
self._request._waitForRecvRequest()
else :
self._xasCli.Close()
if self._onSent :
try :
self._onSent(self._mws2, self)
except Exception as ex :
self._mws2.Log( 'Exception raised from "Response.OnSent" handler: %s' % ex,
self._mws2.ERROR )
# ------------------------------------------------------------------------
def _onClosed(self, xasCli, closedReason) :
if self._stream :
try :
self._stream.close()
except :
pass
self._stream = None
self._sendingBuf = None
# ------------------------------------------------------------------------
def _makeBaseResponseHdr(self, code) :
reason = self._RESPONSE_CODES.get(code, ('Unknown reason', ))[0]
self._mws2.Log( 'From %s:%s %s%s %s >> [%s] %s'
% ( self._xasCli.CliAddr[0],
self._xasCli.CliAddr[1],
('SSL-' if self.IsSSL else ''),
self._request._method,
self._request._path,
code,
reason ),
self._mws2.DEBUG )
if self._mws2.AllowAllOrigins :
self._acAllowOrigin = self._request.Origin
if self._acAllowOrigin :
self.SetHeader('Access-Control-Allow-Origin', self._acAllowOrigin)
self.SetHeader('Server', 'MicroWebSrv2 by JC`zic')
hdr = ''
for n in self._headers :
hdr += '%s: %s\r\n' % (n, self._headers[n])
resp = 'HTTP/1.1 %s %s\r\n%s\r\n' % (code, reason, hdr)
return resp.encode('ISO-8859-1')
# ------------------------------------------------------------------------
def _makeResponseHdr(self, code) :
if code >= 200 and code < 300 :
self._keepAlive = self._request.IsKeepAlive
else :
self._keepAlive = False
if self._keepAlive :
self.SetHeader('Connection', 'Keep-Alive')
self.SetHeader('Keep-Alive', 'timeout=%s' % self._mws2._timeoutSec)
else :
self.SetHeader('Connection', 'Close')
if self._allowCaching :
self.SetHeader('Cache-Control', 'public, max-age=31536000')
else :
self.SetHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
if self._contentType :
ct = self._contentType
if self._contentCharset :
ct += '; charset=%s' % self._contentCharset
self.SetHeader('Content-Type', ct)
if self._contentLength :
self.SetHeader('Content-Length', self._contentLength)
return self._makeBaseResponseHdr(code)
# ------------------------------------------------------------------------
def SwitchingProtocols(self, upgrade) :
if not isinstance(upgrade, str) or len(upgrade) == 0 :
raise ValueError('"upgrade" must be a not empty string.')
if self._hdrSent :
self._mws2.Log( 'Response headers already sent for request "%s".'
% self._request._path,
self._mws2.WARNING )
return
self.SetHeader('Connection', 'Upgrade')
self.SetHeader('Upgrade', upgrade)
data = self._makeBaseResponseHdr(101)
self._xasCli.AsyncSendData(data)
self._hdrSent = True
# ------------------------------------------------------------------------
def ReturnStream(self, code, stream) :
if not isinstance(code, int) or code <= 0 :
raise ValueError('"code" must be a positive integer.')
if not hasattr(stream, 'readinto') or not hasattr(stream, 'close') :
raise ValueError('"stream" must be a readable buffer protocol object.')
if self._hdrSent :
self._mws2.Log( 'Response headers already sent for request "%s".'
% self._request._path,
self._mws2.WARNING )
try :
stream.close()
except :
pass
return
if self._request._method != 'HEAD' :
self._stream = stream
self._sendingBuf = memoryview(self._xasCli.SendingBuffer)
self._xasCli.OnClosed = self._onClosed
else :
try :
stream.close()
except :
pass
if not self._contentType :
self._contentType = 'application/octet-stream'
if not self._contentLength :
self.SetHeader('Transfer-Encoding', 'chunked')
data = self._makeResponseHdr(code)
self._xasCli.AsyncSendData(data, onDataSent=self._onDataSent)
self._hdrSent = True
# ------------------------------------------------------------------------
def Return(self, code, content=None) :
if not isinstance(code, int) or code <= 0 :
raise ValueError('"code" must be a positive integer.')
if self._hdrSent :
self._mws2.Log( 'Response headers already sent for request "%s".'
% self._request._path,
self._mws2.WARNING )
return
if not content :
respCode = self._RESPONSE_CODES.get(code, ('Unknown reason', ''))
self._contentType = 'text/html'
content = self._CODE_CONTENT_TMPL % { 'code' : code,
'reason' : respCode[0],
'message' : respCode[1] }
if isinstance(content, str) :
content = content.encode('UTF-8')
if not self._contentType :
self._contentType = 'text/html'
self._contentCharset = 'UTF-8'
elif not self._contentType :
self._contentType = 'application/octet-stream'
self._contentLength = len(content)
data = self._makeResponseHdr(code)
if self._request._method != 'HEAD' :
data += bytes(content)
self._xasCli.AsyncSendData(data, onDataSent=self._onDataSent)
self._hdrSent = True
# ------------------------------------------------------------------------
def ReturnJSON(self, code, obj) :
if not isinstance(code, int) or code <= 0 :
raise ValueError('"code" must be a positive integer.')
self._contentType = 'application/json'
try :
content = json.dumps(obj)
except :
raise ValueError('"obj" cannot be converted into JSON format.')
self.Return(code, content)
# ------------------------------------------------------------------------
def ReturnOk(self, content=None) :
self.Return(200, content)
# ------------------------------------------------------------------------
def ReturnOkJSON(self, obj) :
self.ReturnJSON(200, obj)
# ------------------------------------------------------------------------
def ReturnFile(self, filename, attachmentName=None) :
if not isinstance(filename, str) or len(filename) == 0 :
raise ValueError('"filename" must be a not empty string.')
if attachmentName is not None and not isinstance(attachmentName, str) :
raise ValueError('"attachmentName" must be a string or None.')
try :
size = stat(filename)[6]
except :
self.ReturnNotFound()
return
try :
file = open(filename, 'rb')
except :
self.ReturnForbidden()
return
if attachmentName :
cd = 'attachment; filename="%s"' % attachmentName.replace('"', "'")
self.SetHeader('Content-Disposition', cd)
if not self._contentType :
self._contentType = self._mws2.GetMimeTypeFromFilename(filename)
self._contentLength = size
self.ReturnStream(200, file)
# ------------------------------------------------------------------------
def ReturnNotModified(self) :
self.Return(304)
# ------------------------------------------------------------------------
def ReturnRedirect(self, location) :
if not isinstance(location, str) or len(location) == 0 :
raise ValueError('"location" must be a not empty string.')
self.SetHeader('Location', location)
self.Return(307)
# ------------------------------------------------------------------------
def ReturnBadRequest(self) :
self.Return(400)
# ------------------------------------------------------------------------
def ReturnUnauthorized(self, typeName, realm=None) :
if not isinstance(typeName, str) or len(typeName) == 0 :
raise ValueError('"typeName" must be a not empty string.')
if realm is not None and not isinstance(realm, str) :
raise ValueError('"realm" must be a string or None.')
wwwAuth = typeName
if realm :
wwwAuth += (' realm="%s"' % realm.replace('"', "'")) if realm else ''
self.SetHeader('WWW-Authenticate', wwwAuth)
self.Return(401)
# ------------------------------------------------------------------------
def ReturnForbidden(self) :
self.Return(403)
# ------------------------------------------------------------------------
def ReturnNotFound(self) :
if self._mws2._notFoundURL :
self.ReturnRedirect(self._mws2._notFoundURL)
else :
self.Return(404)
# ------------------------------------------------------------------------
def ReturnMethodNotAllowed(self) :
self.Return(405)
# ------------------------------------------------------------------------
def ReturnEntityTooLarge(self) :
self.Return(413)
# ------------------------------------------------------------------------
def ReturnInternalServerError(self) :
self.Return(500)
# ------------------------------------------------------------------------
def ReturnNotImplemented(self) :
self.Return(501)
# ------------------------------------------------------------------------
def ReturnServiceUnavailable(self) :
self.Return(503)
# ------------------------------------------------------------------------
def ReturnBasicAuthRequired(self) :
self.ReturnUnauthorized('Basic')
# ------------------------------------------------------------------------
def ReturnBearerAuthRequired(self) :
self.ReturnUnauthorized('Bearer')
# ------------------------------------------------------------------------
@property
def Request(self) :
return self._request
# ------------------------------------------------------------------------
@property
def UserAddress(self) :
return self._xasCli.CliAddr
# ------------------------------------------------------------------------
@property
def IsSSL(self) :
return self._xasCli.IsSSL
# ------------------------------------------------------------------------
@property
def AllowCaching(self) :
return self._allowCaching
@AllowCaching.setter
def AllowCaching(self, value) :
if not isinstance(value, bool) :
raise ValueError('"AllowCaching" must be a boolean.')
self._allowCaching = value
# ------------------------------------------------------------------------
@property
def AccessControlAllowOrigin(self) :
return self._acAllowOrigin
@AccessControlAllowOrigin.setter
def AccessControlAllowOrigin(self, value) :
if value is not None and not isinstance(value, str) :
raise ValueError('"AccessControlAllowOrigin" must be a string or None.')
self._acAllowOrigin = value
# ------------------------------------------------------------------------
@property
def ContentType(self) :
return self._contentType
@ContentType.setter
def ContentType(self, value) :
if value is not None and not isinstance(value, str) :
raise ValueError('"ContentType" must be a string or None.')
self._contentType = value
# ------------------------------------------------------------------------
@property
def ContentCharset(self) :
return self._contentCharset
@ContentCharset.setter
def ContentCharset(self, value) :
if value is not None and not isinstance(value, str) :
raise ValueError('"ContentCharset" must be a string or None.')
self._contentCharset = value
# ------------------------------------------------------------------------
@property
def ContentLength(self) :
return self._contentLength
@ContentLength.setter
def ContentLength(self, value) :
if not isinstance(value, int) or value < 0 :
raise ValueError('"ContentLength" must be a positive integer or zero.')
self._contentLength = value
# ------------------------------------------------------------------------
@property
def HeadersSent(self) :
return self._hdrSent
# ------------------------------------------------------------------------
@property
def OnSent(self) :
return self._onSent
@OnSent.setter
def OnSent(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnSent" must be a function.')
self._onSent = value
# ============================================================================
# ============================================================================
# ============================================================================
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,218 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
class UrlUtils :
# ----------------------------------------------------------------------------
@staticmethod
def Quote(s, safe='/') :
r = ''
for c in str(s) :
if (c >= 'a' and c <= 'z') or \
(c >= '0' and c <= '9') or \
(c >= 'A' and c <= 'Z') or \
(c in '.-_') or (c in safe) :
r += c
else :
for b in c.encode('UTF-8') :
r += '%%%02X' % b
return r
# ----------------------------------------------------------------------------
@staticmethod
def UrlEncode(s) :
return UrlUtils.Quote(s, ';/?:@&=+$,')
# ----------------------------------------------------------------------------
@staticmethod
def Unquote(s) :
r = str(s).split('%')
try :
b = r[0].encode()
for i in range(1, len(r)) :
try :
b += bytes([int(r[i][:2], 16)]) + r[i][2:].encode()
except :
b += b'%' + r[i].encode()
return b.decode('UTF-8')
except :
return str(s)
# ----------------------------------------------------------------------------
@staticmethod
def UnquotePlus(s) :
return UrlUtils.Unquote(str(s).replace('+', ' '))
# ============================================================================
# ===( Class Url )============================================================
# ============================================================================
class Url :
def __init__(self, url='') :
self.URL = url
# ------------------------------------------------------------------------
def __repr__(self) :
return self.URL if self.URL is not None else ''
# ------------------------------------------------------------------------
def IsHttps(self) :
return (self._proto == 'https')
# ------------------------------------------------------------------------
@property
def URL(self) :
host = self.Host
if host != '' :
proto = self.Proto
port = self.Port
if ( proto == 'http' and port == 80 ) or \
( proto == 'https' and port == 443 ) :
port = ''
else :
port = ':' + str(port)
url = proto + '://' + host + port + self.Path
url = UrlUtils.UrlEncode(url)
qs = self.QueryString
if qs != '' :
return url + '?' + qs
return url
return None
@URL.setter
def URL(self, value) :
try :
s = str(value)
if '://' in s :
proto, s = s.split('://', 1)
else :
proto = 'http'
except :
raise ValueError('URL error (%s)' % value)
self.Proto = proto
if '/' in s :
host, path = s.split('/', 1)
elif '?' in s :
host, path = s.split('?', 1)
path = '?' + path
else :
host = s
path = ''
if ':' in host :
try :
host, port = host.split(':')
self.Port = port
except :
raise ValueError('URL host:port error (%s)' % host)
self.Host = host
self._queryParams = { }
self.Path = path
# ------------------------------------------------------------------------
@property
def Proto(self) :
return self._proto
@Proto.setter
def Proto(self, value) :
value = str(value).lower()
if value == 'http' :
self._port = 80
elif value == 'https' :
self._port = 443
else :
raise ValueError('Unsupported URL protocol (%s)' % value)
self._proto = value
# ------------------------------------------------------------------------
@property
def Host(self) :
return self._host
@Host.setter
def Host(self, value) :
self._host = UrlUtils.UnquotePlus(value)
# ------------------------------------------------------------------------
@property
def Port(self) :
return self._port
@Port.setter
def Port(self, value) :
try :
p = int(value)
except :
raise ValueError('Port must be an integer value')
if p <= 0 or p >= 65536 :
raise ValueError('Port must be greater than 0 and less than 65536')
self._port = p
# ------------------------------------------------------------------------
@property
def Path(self) :
return self._path
@Path.setter
def Path(self, value) :
x = value.split('?', 1)
if len(x[0]) > 0 :
if x[0][0] != '/' :
x[0] = '/' + x[0]
self._path = UrlUtils.UnquotePlus(x[0])
else :
self._path = '/'
if len(x) == 2 :
self.QueryString = x[1]
# ------------------------------------------------------------------------
@property
def QueryString(self) :
r = ''
for param in self._queryParams :
if param != '' :
if r != '' :
r += '&'
r += UrlUtils.Quote(param) + '=' + UrlUtils.Quote(self._queryParams[param])
return r
@QueryString.setter
def QueryString(self, value) :
self._queryParams = { }
for x in value.split('&') :
param = x.split('=', 1)
if param[0] != '' :
value = UrlUtils.Unquote(param[1]) if len(param) > 1 else ''
self._queryParams[UrlUtils.Unquote(param[0])] = value
# ------------------------------------------------------------------------
@property
def QueryParams(self) :
return self._queryParams
@QueryParams.setter
def QueryParams(self, value) :
if not isinstance(value, dict) :
raise ValueError('QueryParams must be a dict')
self._queryParams = value
# ============================================================================
# ============================================================================
# ============================================================================
@@ -0,0 +1,544 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from . import *
from .httpRequest import HttpRequest
from os import stat
from sys import implementation
from _thread import stack_size
# ============================================================================
# ===( MicroWebSrv2 )=========================================================
# ============================================================================
class MicroWebSrv2Exception(Exception) :
pass
# ----------------------------------------------------------------------------
class MicroWebSrv2 :
_DEFAULT_PAGES = [
"index.html",
"index.htm",
"default.html",
"default.htm"
]
_MIME_TYPES = {
".txt" : "text/plain",
".htm" : "text/html",
".html" : "text/html",
".css" : "text/css",
".csv" : "text/csv",
".js" : "application/javascript",
".xml" : "application/xml",
".xhtml" : "application/xhtml+xml",
".json" : "application/json",
".zip" : "application/zip",
".pdf" : "application/pdf",
".ts" : "application/typescript",
".woff" : "font/woff",
".woff2" : "font/woff2",
".ttf" : "font/ttf",
".otf" : "font/otf",
".jpg" : "image/jpeg",
".jpeg" : "image/jpeg",
".png" : "image/png",
".gif" : "image/gif",
".svg" : "image/svg+xml",
".ico" : "image/x-icon"
}
_HTML_ESCAPE_CHARS = {
"&" : "&amp;",
'"' : "&quot;",
"'" : "&apos;",
">" : "&gt;",
"<" : "&lt;"
}
_STAT_MODE_DIR = 1 << 14
DEBUG = 0x00
INFO = 0x01
WARNING = 0x02
ERROR = 0x03
MSG_TYPE_STR = {
DEBUG : 'DEBUG',
INFO : 'INFO',
WARNING : 'WARNING',
ERROR : 'ERROR'
}
# ------------------------------------------------------------------------
_modules = { }
# ------------------------------------------------------------------------
def __init__(self) :
self._backlog = None
self._slotsCount = None
self._slotsSize = None
self._keepAlloc = None
self._maxContentLen = None
self._bindAddr = ('0.0.0.0', 80)
self._sslContext = None
self._rootPath = 'www'
self._timeoutSec = 2
self._notFoundURL = None
self._allowAllOrigins = False
self._corsAllowAll = False
self._onLogging = None
self._xasSrv = None
self._xasPool = None
self.SetNormalConfig()
# ------------------------------------------------------------------------
@staticmethod
def _physPathExists(physPath) :
try :
stat(physPath)
return True
except :
return False
# ------------------------------------------------------------------------
@staticmethod
def _physPathIsDir(physPath) :
return (stat(physPath)[0] & MicroWebSrv2._STAT_MODE_DIR != 0)
# ------------------------------------------------------------------------
@staticmethod
def LoadModule(modName) :
if not isinstance(modName, str) or len(modName) == 0 :
raise ValueError('"modName" must be a not empty string.')
if modName in MicroWebSrv2._modules :
raise MicroWebSrv2Exception('Module "%s" is already loaded.' % modName)
try :
modPath = MicroWebSrv2.__module__.split('microWebSrv2')[0] \
+ ('mods.%s' % modName)
print('loadmod',modPath)
module = getattr(__import__(modPath).mods, modName)
modClass = getattr(module, modName)
if type(modClass) is not type :
raise Exception
modInstance = modClass()
MicroWebSrv2._modules[modName] = modInstance
return modInstance
except :
raise MicroWebSrv2Exception('Cannot load module "%s".' % modName)
# ------------------------------------------------------------------------
@staticmethod
def HTMLEscape(s) :
if not isinstance(s, str) :
raise ValueError('"s" must be a string.')
return ''.join(MicroWebSrv2._HTML_ESCAPE_CHARS.get(c, c) for c in s)
# ------------------------------------------------------------------------
@staticmethod
def AddDefaultPage(filename) :
if not isinstance(filename, str) or len(filename) == 0 :
raise ValueError('"filename" must be a not empty string.')
MicroWebSrv2._DEFAULT_PAGES.append(filename)
# ------------------------------------------------------------------------
@staticmethod
def AddMimeType(ext, mimeType) :
if not isinstance(ext, str) or len(ext) == 0 :
raise ValueError('"ext" must be a not empty string.')
if not isinstance(mimeType, str) or len(mimeType) == 0 :
raise ValueError('"mimeType" must be a not empty string.')
MicroWebSrv2._MIME_TYPES[ext.lower()] = mimeType.lower()
# ------------------------------------------------------------------------
@staticmethod
def GetMimeTypeFromFilename(filename) :
filename = filename.lower()
for ext in MicroWebSrv2._MIME_TYPES :
if filename.endswith(ext) :
return MicroWebSrv2._MIME_TYPES[ext]
return None
# ------------------------------------------------------------------------
def StartInPool(self, asyncSocketsPool) :
if not isinstance(asyncSocketsPool, XAsyncSocketsPool) :
raise ValueError('"asyncSocketsPool" must be a XAsyncSocketsPool class.')
if self._xasSrv :
raise MicroWebSrv2Exception('Server is already running.')
try :
xBufSlots = XBufferSlots( slotsCount = self._slotsCount,
slotsSize = self._slotsSize,
keepAlloc = self._keepAlloc )
except :
raise MicroWebSrv2Exception('Not enough memory to allocate slots.')
try :
self._xasSrv = XAsyncTCPServer.Create( asyncSocketsPool = asyncSocketsPool,
srvAddr = self._bindAddr,
srvBacklog = self._backlog,
bufSlots = xBufSlots )
except :
raise MicroWebSrv2Exception('Cannot bind server on %s:%s.' % self._bindAddr)
self._xasSrv.OnClientAccepted = self._onSrvClientAccepted
self._xasSrv.OnClosed = self._onSrvClosed
self.Log('Server listening on %s:%s.' % self._bindAddr, MicroWebSrv2.INFO)
# ------------------------------------------------------------------------
def StartManaged(self, parllProcCount=1, procStackSize=0) :
if not isinstance(parllProcCount, int) or parllProcCount < 0 :
raise ValueError('"parllProcCount" must be a positive integer or zero.')
if not isinstance(procStackSize, int) or procStackSize < 0 :
raise ValueError('"procStackSize" must be a positive integer or zero.')
if self._xasSrv :
raise MicroWebSrv2Exception('Server is already running.')
if procStackSize == 0 and implementation.name == 'micropython' :
procStackSize = 8*1024
try :
saveStackSize = stack_size(procStackSize)
except Exception as ex :
raise ValueError('"procStackSize" of %s is not correct (%s).' % (procStackSize, ex))
self._xasPool = XAsyncSocketsPool()
try :
self.StartInPool(self._xasPool)
try :
self.Log('Starts the managed pool to wait for I/O events.', MicroWebSrv2.INFO)
self._xasPool.AsyncWaitEvents(threadsCount=parllProcCount)
except :
raise MicroWebSrv2Exception('Not enough memory to start %s parallel processes.' % parllProcCount)
except Exception as ex :
self.Stop()
raise ex
finally :
try :
stack_size(saveStackSize)
except :
pass
# ------------------------------------------------------------------------
def Stop(self) :
if self._xasSrv :
self._xasSrv.Close()
self._xasSrv = None
if self._xasPool :
self.Log('Stops the managed pool.', MicroWebSrv2.INFO)
self._xasPool.StopWaitEvents()
self._xasPool = None
# ------------------------------------------------------------------------
def Log(self, msg, msgType) :
if self._onLogging :
try :
self._onLogging(self, str(msg), msgType)
return
except Exception as ex :
msgType = MicroWebSrv2.ERROR
msg = 'Exception raised from "OnLoggin" handler: %s' % ex
t = MicroWebSrv2.MSG_TYPE_STR.get(msgType, None)
if t :
print('MWS2-%s> %s' % (t, msg))
# ------------------------------------------------------------------------
def ResolvePhysicalPath(self, urlPath) :
if not isinstance(urlPath, str) or len(urlPath) == 0 :
raise ValueError('"urlPath" must be a not empty string.')
try :
physPath = self._rootPath + urlPath.replace('..', '/')
if physPath.endswith('/') :
physPath = physPath[:-1]
if MicroWebSrv2._physPathIsDir(physPath) :
for filename in MicroWebSrv2._DEFAULT_PAGES :
p = physPath + '/' + filename
if MicroWebSrv2._physPathExists(p) :
return p
return physPath
except :
return None
# ------------------------------------------------------------------------
def _onSrvClientAccepted(self, xAsyncTCPServer, xAsyncTCPClient) :
if self._sslContext :
try :
xAsyncTCPClient.StartSSLContext( sslContext = self._sslContext,
serverSide = True )
except :
self.Log( 'SSL connection failed from %s:%s.'
% xAsyncTCPClient.CliAddr,
MicroWebSrv2.DEBUG )
xAsyncTCPClient.Close()
return
HttpRequest(self, xAsyncTCPClient)
# ------------------------------------------------------------------------
def _onSrvClosed(self, xAsyncTCPServer, closedReason) :
self.Log('Server %s:%s closed.' % self._bindAddr, MicroWebSrv2.INFO)
# ------------------------------------------------------------------------
def _validateChangeConf(self, name='Configuration') :
if self._xasSrv :
raise MicroWebSrv2Exception('%s cannot be changed while the server is running.' % name)
# ------------------------------------------------------------------------
def EnableSSL(self, certFile, keyFile, caFile=None) :
import ssl
if not hasattr(ssl, 'SSLContext') :
raise MicroWebSrv2Exception('Unable to use SSL (implementation not supported).')
if not isinstance(certFile, str) or len(certFile) == 0 :
raise ValueError('"certFile" must be a not empty string.')
if not isinstance(keyFile, str) or len(keyFile) == 0 :
raise ValueError('"keyFile" must be a not empty string.')
if caFile is not None and not isinstance(caFile, str) :
raise ValueError('"caFile" must be a string or None.')
self._validateChangeConf()
try :
ctx = ssl.create_default_context( ssl.Purpose.CLIENT_AUTH,
cafile = caFile )
except :
raise ValueError('"caFile" must indicate a valid PEM file.')
try :
ctx.load_cert_chain(certfile=certFile, keyfile=keyFile)
except :
raise ValueError('"certFile" and "keyFile" must indicate the valid certificate and key files.')
self._sslContext = ctx
if self._bindAddr[1] == 80 :
self._bindAddr = (self._bindAddr[0], 443)
# ------------------------------------------------------------------------
def DisableSSL(self) :
self._validateChangeConf()
self._sslContext = None
if self._bindAddr[1] == 443 :
self._bindAddr = (self._bindAddr[0], 80)
# ------------------------------------------------------------------------
def SetEmbeddedConfig(self) :
self._validateChangeConf()
self._backlog = 8
self._slotsCount = 16
self._slotsSize = 1024
self._keepAlloc = True
self._maxContentLen = 16*1024
# ------------------------------------------------------------------------
def SetLightConfig(self) :
self._validateChangeConf()
self._backlog = 64
self._slotsCount = 128
self._slotsSize = 1024
self._keepAlloc = True
self._maxContentLen = 512*1024
# ------------------------------------------------------------------------
def SetNormalConfig(self) :
self._validateChangeConf()
self._backlog = 256
self._slotsCount = 512
self._slotsSize = 4*1024
self._keepAlloc = True
self._maxContentLen = 2*1024*1024
# ------------------------------------------------------------------------
def SetLargeConfig(self) :
self._validateChangeConf()
self._backlog = 512
self._slotsCount = 2048
self._slotsSize = 16*1024
self._keepAlloc = True
self._maxContentLen = 8*1024*1024
# ------------------------------------------------------------------------
@property
def IsRunning(self) :
return ( self._xasPool is not None and \
self._xasPool.WaitEventsProcessing and \
self._xasSrv is not None )
# ------------------------------------------------------------------------
@property
def ConnQueueCapacity(self) :
return self._backlog
@ConnQueueCapacity.setter
def ConnQueueCapacity(self, value) :
if not isinstance(value, int) or value <= 0 :
raise ValueError('"ConnQueueCapacity" must be a positive integer.')
self._validateChangeConf('"ConnQueueCapacity"')
self._backlog = value
# ------------------------------------------------------------------------
@property
def BufferSlotsCount(self) :
return self._slotsCount
@BufferSlotsCount.setter
def BufferSlotsCount(self, value) :
if not isinstance(value, int) or value <= 0 :
raise ValueError('"BufferSlotsCount" must be a positive integer.')
self._validateChangeConf('"BufferSlotsCount"')
self._slotsCount = value
# ------------------------------------------------------------------------
@property
def BufferSlotSize(self) :
return self._slotsSize
@BufferSlotSize.setter
def BufferSlotSize(self, value) :
if not isinstance(value, int) or value <= 0 :
raise ValueError('"BufferSlotSize" must be a positive integer.')
self._validateChangeConf('"BufferSlotSize"')
self._slotsSize = value
# ------------------------------------------------------------------------
@property
def KeepAllocBufferSlots(self) :
return self._keepAlloc
@KeepAllocBufferSlots.setter
def KeepAllocBufferSlots(self, value) :
if not isinstance(value, bool) :
raise ValueError('"KeepAllocBufferSlots" must be a boolean.')
self._validateChangeConf('"KeepAllocBufferSlots"')
self._keepAlloc = value
# ------------------------------------------------------------------------
@property
def MaxRequestContentLength(self) :
return self._maxContentLen
@MaxRequestContentLength.setter
def MaxRequestContentLength(self, value) :
if not isinstance(value, int) or value <= 0 :
raise ValueError('"MaxRequestContentLength" must be a positive integer.')
self._maxContentLen = value
# ------------------------------------------------------------------------
@property
def BindAddress(self) :
return self._bindAddr
@BindAddress.setter
def BindAddress(self, value) :
if not value or len(value) != 2 or \
not isinstance(value[0], str) or \
not isinstance(value[1], int) :
raise ValueError('"BindAddress" must be a tuple of (ipAddr, tcpPort).')
if value[1] < 1 or value[1] > 65535 :
raise ValueError('"BindAddress" has an incorrect port number.')
self._validateChangeConf('"BindAddress"')
self._bindAddr = value
# ------------------------------------------------------------------------
@property
def IsSSLEnabled(self) :
return (self._sslContext is not None)
# ------------------------------------------------------------------------
@property
def RootPath(self) :
return self._rootPath
@RootPath.setter
def RootPath(self, value) :
if not isinstance(value, str) or len(value) == 0 :
raise ValueError('"RootPath" must be a not empty string.')
self._validateChangeConf('"RootPath"')
self._rootPath = (value[:-1] if value.endswith('/') else value)
# ------------------------------------------------------------------------
@property
def RequestsTimeoutSec(self) :
return self._timeoutSec
@RequestsTimeoutSec.setter
def RequestsTimeoutSec(self, value) :
if not isinstance(value, int) or value <= 0 :
raise ValueError('"RequestsTimeoutSec" must be a positive integer.')
self._timeoutSec = value
# ------------------------------------------------------------------------
@property
def NotFoundURL(self) :
return self._notFoundURL
@NotFoundURL.setter
def NotFoundURL(self, value) :
if value is not None and not isinstance(value, str) :
raise ValueError('"NotFoundURL" must be a string or None.')
self._notFoundURL = value
# ------------------------------------------------------------------------
@property
def AllowAllOrigins(self) :
return self._allowAllOrigins
@AllowAllOrigins.setter
def AllowAllOrigins(self, value) :
if not isinstance(value, bool) :
raise ValueError('"AllowAllOrigins" must be a boolean.')
self._allowAllOrigins = value
# ------------------------------------------------------------------------
@property
def CORSAllowAll(self) :
return self._corsAllowAll
@CORSAllowAll.setter
def CORSAllowAll(self, value) :
if not isinstance(value, bool) :
raise ValueError('"CORSAllowAll" must be a boolean.')
self._corsAllowAll = value
# ------------------------------------------------------------------------
@property
def OnLogging(self) :
return self._onLogging
@OnLogging.setter
def OnLogging(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnLogging" must be a function.')
self._onLogging = value
# ============================================================================
# ============================================================================
# ============================================================================
@@ -0,0 +1,394 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from os import stat
import re
# ============================================================================
# ===( MicroWebSrv2 : PyhtmlTemplate Module )=================================
# ============================================================================
class PyhtmlTemplate :
_CODE_CONTENT_DEBUG = """\
<html>
<head>
<title>MicroWebSrv2</title>
</head>
<body style="font-family: Verdana; background-color: Black; color: White;">
<h2>MicroWebSrv2 - [500] Internal Server Error</h2>
<div style="margin: 20px;">
<h3>PyhtmlTemplate Module Debug</h3>
<div style="padding: 15px; background-color: Crimson;">
Exception in %(path)s<br />
%(message)s
</div>
</div>
</body>
</html>
"""
# ------------------------------------------------------------------------
def __init__(self) :
self._showDebug = False
self._pyGlobalVars = { }
# ------------------------------------------------------------------------
def OnRequest(self, microWebSrv2, request) :
if (request.Method == 'GET' or request.Method == 'HEAD') and \
request.Path.lower().endswith('.pyhtml') :
filepath = microWebSrv2.ResolvePhysicalPath(request.Path)
self.ReturnTemplate(microWebSrv2, request, filepath)
# ------------------------------------------------------------------------
def ReturnTemplate(self, microWebSrv2, request, filepath):
if not filepath:
request.Response.ReturnNotFound()
return
try :
with open(filepath, 'r') as file :
code = file.read()
except :
request.Response.ReturnForbidden()
return
try :
self._pyGlobalVars['Request'] = request
codeTemplate = CodeTemplate(code, microWebSrv2.HTMLEscape)
content = codeTemplate.Execute(self._pyGlobalVars, None)
request.Response.ReturnOk(content)
except Exception as ex :
microWebSrv2.Log( 'Exception raised from pyhtml template file "%s": %s' % (filepath, ex),
microWebSrv2.ERROR )
if self._showDebug :
request.Response.Return( 500,
PyhtmlTemplate._CODE_CONTENT_DEBUG
% { 'path' : filepath,
'message' : ex } )
else :
request.Response.ReturnInternalServerError()
# ------------------------------------------------------------------------
def SetGlobalVar(self, globalVarName, globalVar) :
if not isinstance(globalVarName, str) or len(globalVarName) == 0 :
raise ValueError('"globalVarName" must be a not empty string.')
self._pyGlobalVars[globalVarName] = globalVar
# ------------------------------------------------------------------------
def GetGlobalVar(self, globalVarName) :
if not isinstance(globalVarName, str) or len(globalVarName) == 0 :
raise ValueError('"globalVarName" must be a not empty string.')
try :
return self._pyGlobalVars[globalVarName]
except :
return None
# ------------------------------------------------------------------------
@property
def ShowDebug(self) :
return self._showDebug
@ShowDebug.setter
def ShowDebug(self, value) :
if not isinstance(value, bool) :
raise ValueError('"ShowDebug" must be a boolean.')
self._showDebug = value
# ============================================================================
# ===( CodeTemplate )=========================================================
# ============================================================================
class CodeTemplateException(Exception) :
pass
class CodeTemplate :
# ------------------------------------------------------------------------
TOKEN_OPEN = '{{'
TOKEN_CLOSE = '}}'
TOKEN_OPEN_LEN = len(TOKEN_OPEN)
TOKEN_CLOSE_LEN = len(TOKEN_CLOSE)
INSTRUCTION_PYTHON = 'py'
INSTRUCTION_IF = 'if'
INSTRUCTION_ELIF = 'elif'
INSTRUCTION_ELSE = 'else'
INSTRUCTION_FOR = 'for'
INSTRUCTION_END = 'end'
RE_IDENTIFIER = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*$')
# ------------------------------------------------------------------------
def __init__(self, code, escapeStrFunc=None) :
self._code = code
self._escapeStrFunc = escapeStrFunc
self._pos = 0
self._endPos = len(code)-1
self._line = 1
self._pyGlobalVars = { }
self._pyLocalVars = { }
self._rendered = ''
self._instructions = {
CodeTemplate.INSTRUCTION_PYTHON : self._processInstructionPYTHON,
CodeTemplate.INSTRUCTION_IF : self._processInstructionIF,
CodeTemplate.INSTRUCTION_ELIF : self._processInstructionELIF,
CodeTemplate.INSTRUCTION_ELSE : self._processInstructionELSE,
CodeTemplate.INSTRUCTION_FOR : self._processInstructionFOR,
CodeTemplate.INSTRUCTION_END : self._processInstructionEND
}
# ------------------------------------------------------------------------
def Validate(self, pyGlobalVars=None, pyLocalVars=None) :
try :
self._parseCode(pyGlobalVars, pyLocalVars, execute=False)
return None
except Exception as ex :
return str(ex)
# ----------------------------------------------------------------------------
def Execute(self, pyGlobalVars=None, pyLocalVars=None) :
try :
self._parseCode(pyGlobalVars, pyLocalVars, execute=True)
return self._rendered
except Exception as ex :
raise CodeTemplateException(str(ex))
# ------------------------------------------------------------------------
def _parseCode(self, pyGlobalVars, pyLocalVars, execute) :
self._pos = 0
self._line = 1
self._pyGlobalVars = (pyGlobalVars if isinstance(pyGlobalVars, dict) else { })
self._pyLocalVars = (pyLocalVars if isinstance(pyLocalVars, dict) else { })
self._rendered = ''
self._pyGlobalVars['print'] = self._renderingPrint
newTokenToProcess = self._parseBloc(execute)
if newTokenToProcess is not None :
raise CodeTemplateException( '"%s" instruction is not valid here (line %s)'
% (newTokenToProcess, self._line) )
# ------------------------------------------------------------------------
def _parseBloc(self, execute) :
while True :
idx = self._code.find(CodeTemplate.TOKEN_OPEN, self._pos)
end = (idx < 0)
if end :
idx = self._endPos+1
code = self._code[self._pos:idx]
self._line += code.count('\n')
if execute :
self._rendered += code
if end :
self._pos = idx
return None
self._pos = idx + CodeTemplate.TOKEN_OPEN_LEN
idx = self._code.find(CodeTemplate.TOKEN_CLOSE, self._pos)
if idx < 0 :
raise CodeTemplateException('"%s" is required but the end of code has been found' % CodeTemplate.TOKEN_CLOSE)
tokenContent = self._code[self._pos:idx].strip()
self._line += tokenContent.count('\n')
self._pos = idx + CodeTemplate.TOKEN_CLOSE_LEN
newTokenToProcess = self._processToken(tokenContent, execute)
if newTokenToProcess is not None :
return newTokenToProcess
# ------------------------------------------------------------------------
def _renderingPrint(self, s) :
self._rendered += str(s)
# ------------------------------------------------------------------------
def _processToken(self, tokenContent, execute) :
parts = tokenContent.split(' ', 1)
instructName = parts[0].strip()
instructBody = parts[1].strip() if len(parts) > 1 else None
if len(instructName) == 0 :
raise CodeTemplateException( '"%s %s" : instruction is missing (line %s)'
% (CodeTemplate.TOKEN_OPEN, CodeTemplate.TOKEN_CLOSE, self._line) )
newTokenToProcess = None
if instructName in self._instructions :
newTokenToProcess = self._instructions[instructName](instructBody, execute)
elif execute :
try :
ret = eval( tokenContent,
self._pyGlobalVars,
self._pyLocalVars )
if ret is not None :
if (self._escapeStrFunc is not None) :
self._rendered += self._escapeStrFunc(str(ret))
else :
self._rendered += str(ret)
except Exception as ex :
raise CodeTemplateException('%s (line %s)' % (ex, self._line))
return newTokenToProcess
# ------------------------------------------------------------------------
def _processInstructionPYTHON(self, instructionBody, execute) :
if instructionBody is not None :
raise CodeTemplateException( 'Instruction "%s" is invalid (line %s)'
% (CodeTemplate.INSTRUCTION_PYTHON, self._line) )
idx = self._code.find(CodeTemplate.TOKEN_OPEN, self._pos)
if idx < 0 :
raise CodeTemplateException('"%s" is required but the end of code has been found' % CodeTemplate.TOKEN_OPEN)
pyCode = self._code[self._pos:idx]
self._line += pyCode.count('\n')
self._pos = idx + CodeTemplate.TOKEN_OPEN_LEN
idx = self._code.find(CodeTemplate.TOKEN_CLOSE, self._pos)
if idx < 0 :
raise CodeTemplateException('"%s" is required but the end of code has been found' % CodeTemplate.TOKEN_CLOSE)
tokenContent = self._code[self._pos:idx].strip()
self._line += tokenContent.count('\n')
self._pos = idx + CodeTemplate.TOKEN_CLOSE_LEN
if tokenContent != CodeTemplate.INSTRUCTION_END :
raise CodeTemplateException( '"%s" is a bad instruction in a python bloc (line %s)'
% (tokenContent, self._line) )
if execute :
lines = pyCode.split('\n')
indent = ''
for line in lines :
if len(line.strip()) > 0 :
for c in line :
if c == ' ' or c == '\t' :
indent += c
else :
break
break
indentLen = len(indent)
for i in range(len(lines)) :
if lines[i].startswith(indent) :
lines[i] = lines[i][indentLen:] + '\n'
else :
lines[i] += '\n'
pyCode = ''.join(lines)
try :
exec(pyCode, self._pyGlobalVars, self._pyLocalVars)
except Exception as ex :
raise CodeTemplateException('%s (line %s)' % (ex, self._line))
return None
# ------------------------------------------------------------------------
def _processInstructionIF(self, instructionBody, execute) :
if instructionBody is not None :
if execute :
try :
if (' ' not in instructionBody) and \
('=' not in instructionBody) and \
('<' not in instructionBody) and \
('>' not in instructionBody) and \
(instructionBody not in self._pyGlobalVars) and \
(instructionBody not in self._pyLocalVars):
result = False
else:
result = bool(eval(instructionBody, self._pyGlobalVars, self._pyLocalVars))
except Exception as ex :
raise CodeTemplateException('%s (line %s)' % (ex, self._line))
else :
result = False
newTokenToProcess = self._parseBloc(execute and result)
if newTokenToProcess is not None :
if newTokenToProcess == CodeTemplate.INSTRUCTION_END :
return None
elif newTokenToProcess == CodeTemplate.INSTRUCTION_ELSE :
newTokenToProcess = self._parseBloc(execute and not result)
if newTokenToProcess is not None :
if newTokenToProcess == CodeTemplate.INSTRUCTION_END :
return None
raise CodeTemplateException( '"%s" instruction waited (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
raise CodeTemplateException( '"%s" instruction is missing (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
elif newTokenToProcess == CodeTemplate.INSTRUCTION_ELIF :
self._processInstructionIF(self._elifInstructionBody, execute and not result)
return None
raise CodeTemplateException( '"%s" instruction waited (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
raise CodeTemplateException( '"%s" instruction is missing (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
raise CodeTemplateException( '"%s" alone is an incomplete syntax (line %s)'
% (CodeTemplate.INSTRUCTION_IF, self._line) )
# ------------------------------------------------------------------------
def _processInstructionELIF(self, instructionBody, execute) :
if instructionBody is None :
raise CodeTemplateException( '"%s" alone is an incomplete syntax (line %s)'
% (CodeTemplate.INSTRUCTION_ELIF, self._line) )
self._elifInstructionBody = instructionBody
return CodeTemplate.INSTRUCTION_ELIF
# ------------------------------------------------------------------------
def _processInstructionELSE(self, instructionBody, execute) :
if instructionBody is not None :
raise CodeTemplateException( 'Instruction "%s" is invalid (line %s)'
% (CodeTemplate.INSTRUCTION_ELSE, self._line) )
return CodeTemplate.INSTRUCTION_ELSE
# ------------------------------------------------------------------------
def _processInstructionFOR(self, instructionBody, execute) :
if instructionBody is not None :
parts = instructionBody.split(' ', 1)
identifier = parts[0].strip()
if CodeTemplate.RE_IDENTIFIER.match(identifier) is not None and len(parts) > 1 :
parts = parts[1].strip().split(' ', 1)
if parts[0] == 'in' and len(parts) > 1 :
expression = parts[1].strip()
newTokenToProcess = None
beforePos = self._pos
if execute :
try :
result = eval(expression, self._pyGlobalVars, self._pyLocalVars)
except :
raise CodeTemplateException('%s (line %s)' % (str(expression), self._line))
if execute and len(result) > 0 :
for x in result :
self._pyLocalVars[identifier] = x
self._pos = beforePos
newTokenToProcess = self._parseBloc(True)
if newTokenToProcess != CodeTemplate.INSTRUCTION_END :
break
else :
newTokenToProcess = self._parseBloc(False)
if newTokenToProcess is not None :
if newTokenToProcess == CodeTemplate.INSTRUCTION_END :
return None
raise CodeTemplateException( '"%s" instruction waited (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
raise CodeTemplateException( '"%s" instruction is missing (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
raise CodeTemplateException( '"%s %s" is an invalid syntax'
% (CodeTemplate.INSTRUCTION_FOR, instructionBody) )
raise CodeTemplateException( '"%s" alone is an incomplete syntax (line %s)'
% (CodeTemplate.INSTRUCTION_FOR, self._line) )
# ------------------------------------------------------------------------
def _processInstructionEND(self, instructionBody, execute) :
if instructionBody is not None :
raise CodeTemplateException( 'Instruction "%s" is invalid (line %s)'
% (CodeTemplate.INSTRUCTION_END, self._line) )
return CodeTemplate.INSTRUCTION_END
# ============================================================================
# ============================================================================
# ============================================================================
@@ -0,0 +1,477 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from hashlib import sha1
from binascii import b2a_base64
from struct import pack
# ============================================================================
# ===( MicroWebSrv2 : WebSockets Module )=====================================
# ============================================================================
class WebSockets :
_PROTOCOL_VERSION = 13
_HANDSHAKE_SIGN = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
# ------------------------------------------------------------------------
def __init__(self) :
self._onWebSocketProtocol = None
self._onWebSocketAccepted = None
# ------------------------------------------------------------------------
def OnRequest(self, microWebSrv2, request) :
if request.IsUpgrade and request.Upgrade.lower() == 'websocket' :
ver = request.GetHeader('Sec-Websocket-Version')
if ver == str(WebSockets._PROTOCOL_VERSION) :
response = request.Response
key = request.GetHeader('Sec-Websocket-Key')
if key :
try :
key += WebSockets._HANDSHAKE_SIGN
sec = sha1(key.encode()).digest()
sec = b2a_base64(sec).decode().strip()
protocols = request.GetHeader('Sec-WebSocket-Protocol')
response.SetHeader('Sec-WebSocket-Accept', sec)
if protocols and self._onWebSocketProtocol :
protocols = [x.strip() for x in protocols.split(',')]
try :
proto = self._onWebSocketProtocol(microWebSrv2, protocols)
except Exception as ex :
microWebSrv2.Log( 'Exception raised from "WebSockets.OnWebSocketProtocol" handler: %s' % ex,
microWebSrv2.ERROR )
raise ex
if proto in protocols :
response.SetHeader('Sec-WebSocket-Protocol', proto)
response.SwitchingProtocols('websocket')
WebSocket(self, microWebSrv2, request)
except :
response.ReturnInternalServerError()
else :
response.ReturnBadRequest()
# ------------------------------------------------------------------------
@property
def OnWebSocketProtocol(self) :
return self._onWebSocketProtocol
@OnWebSocketProtocol.setter
def OnWebSocketProtocol(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnWebSocketProtocol" must be a function.')
self._onWebSocketProtocol = value
# ------------------------------------------------------------------------
@property
def OnWebSocketAccepted(self) :
return self._onWebSocketAccepted
@OnWebSocketAccepted.setter
def OnWebSocketAccepted(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnWebSocketAccepted" must be a function.')
self._onWebSocketAccepted = value
# ============================================================================
# ===( WebSocket )============================================================
# ============================================================================
class WebSocket :
_OP_FRAME_CONT = 0x00
_OP_FRAME_TEXT = 0x01
_OP_FRAME_BIN = 0x02
_OP_FRAME_CLOSE = 0x08
_OP_FRAME_PING = 0x09
_OP_FRAME_PONG = 0x0A
_MSG_TYPE_TEXT = 0x01
_MSG_TYPE_BIN = 0x02
# ------------------------------------------------------------------------
def __init__(self, wsMod, mws2, request) :
self._mws2 = mws2
self._request = request
self._xasCli = request.XAsyncTCPClient
self._currentMsgType = None
self._currentMsgData = None
self._isClosed = False
self._waitFrameTimeoutSec = 300
self._maxRecvMsgLen = mws2.MaxRequestContentLength
self._onTextMsg = None
self._onBinMsg = None
self._onClosed = None
onWSAccepted = wsMod.OnWebSocketAccepted
self._mws2.Log( '%sWebSocket %s from %s:%s.'
% ( ('SSL-' if request.IsSSL else ''),
'accepted' if onWSAccepted else 'denied',
self._xasCli.CliAddr[0],
self._xasCli.CliAddr[1] ),
self._mws2.INFO )
if not onWSAccepted :
self._close(1001, 'Going away...')
return
self._xasCli.OnClosed = self._onXAsCliClosed
try :
onWSAccepted(self._mws2, self)
except Exception as ex :
self._mws2.Log( 'Exception raised from "WebSockets.OnWebSocketAccepted" handler: %s' % ex,
self._mws2.ERROR )
self._close(1011, 'Unexpected error')
return
self._waitFrame()
# ------------------------------------------------------------------------
def _recvData(self, onRecv, size=None) :
self._xasCli.AsyncRecvData( size = size,
onDataRecv = onRecv,
timeoutSec = self._mws2.RequestsTimeoutSec )
# ------------------------------------------------------------------------
def _onXAsCliClosed(self, xasCli, closedReason) :
self._isClosed = True
if self._onClosed :
try :
self._onClosed(self)
except Exception as ex :
self._mws2.Log( 'Exception raised from "WebSocket.OnClosed" handler: %s' % ex,
self._mws2.ERROR )
# ------------------------------------------------------------------------
def _waitFrame(self) :
def onHdrStartingRecv(xasCli, data, arg) :
fin = data[0] & 0x80 > 0
opcode = data[0] & 0x0F
masked = data[1] & 0x80 > 0
length = data[1] & 0x7F
# Control frame ?
isCtrlFrame = ( opcode != WebSocket._OP_FRAME_TEXT and \
opcode != WebSocket._OP_FRAME_BIN and \
opcode != WebSocket._OP_FRAME_CONT )
if ( isCtrlFrame and not fin ) \
or \
( opcode == WebSocket._OP_FRAME_CONT and \
not self._currentMsgType ) \
or \
( self._currentMsgType and \
( opcode == WebSocket._OP_FRAME_TEXT or \
opcode == WebSocket._OP_FRAME_BIN ) ) :
# Bad frame in the context,
self._close(1002, 'Protocol error (bad frame in the context)')
return
def endOfHeader(dataLen, maskingKey) :
def onPayloadDataRecv(xasCli, data, arg) :
if maskingKey :
for i in range(dataLen) :
data[i] ^= maskingKey[i%4]
if self._currentMsgData :
try :
self._currentMsgData += data
except :
# Frame is too large for memory allocation,
self._close(1009, 'Frame is too large to be processed')
return
else :
self._currentMsgData = data
if fin :
# Frame is fully received,
if self._currentMsgType == WebSocket._MSG_TYPE_TEXT :
# Text frame,
if self._onTextMsg :
try :
msg = bytes(self._currentMsgData).decode('UTF-8')
try :
self._onTextMsg(self, msg)
except Exception as ex :
self._mws2.Log( 'Exception raised from "WebSocket.OnTextMessage" handler: %s' % ex,
self._mws2.ERROR )
self._close(1011, 'Unexpected error while processing text message')
return
except :
self._mws2.Log( 'Error during UTF-8 decoding of websocket text message.',
self._mws2.WARNING )
self._close(1007, 'Error to decode UTF-8 text message')
return
else :
self._close(1003, 'Text messages are not implemented')
return
elif self._currentMsgType == WebSocket._MSG_TYPE_BIN :
# Binary frame,
if self._onBinMsg :
try :
self._onBinMsg(self, bytes(self._currentMsgData))
except Exception as ex :
self._mws2.Log( 'Exception raised from "WebSocket.OnBinaryMessage" handler: %s' % ex,
self._mws2.ERROR )
self._close(1011, 'Unexpected error while processing binary message')
return
else :
self._close(1003, 'Binary messages are not implemented')
return
self._currentMsgType = None
self._currentMsgData = None
self._waitFrame()
# - End of onPayloadDataRecv -
if not isCtrlFrame :
# Message frame or continuation frame,
if self._maxRecvMsgLen :
l = dataLen
if self._currentMsgData :
l += len(self._currentMsgData)
if l > self._maxRecvMsgLen :
# Message length exceeds the defined limit,
self._close(1009, 'Frame is too large to be processed')
return
if opcode == WebSocket._OP_FRAME_TEXT :
self._currentMsgType = WebSocket._MSG_TYPE_TEXT
elif opcode == WebSocket._OP_FRAME_BIN :
self._currentMsgType = WebSocket._MSG_TYPE_BIN
try :
self._recvData(onPayloadDataRecv, dataLen)
except :
# Frame is too large for memory allocation,
self._close(1009, 'Frame is too large to be processed')
elif opcode == WebSocket._OP_FRAME_PING :
# Ping control frame,
if dataLen > 0 :
def onPingDataRecv(xasCli, data, arg) :
data = bytearray(data)
self._sendFrame(WebSocket._OP_FRAME_PONG, data)
self._waitFrame()
self._recvData(onPingDataRecv, dataLen)
else :
self._sendFrame(WebSocket._OP_FRAME_PONG)
self._waitFrame()
elif opcode == WebSocket._OP_FRAME_PONG :
# Pong control frame,
if dataLen > 0 :
def onPongDataRecv(xasCli, data, arg) :
self._waitFrame()
self._recvData(onPongDataRecv, dataLen)
else :
self._waitFrame()
elif opcode == WebSocket._OP_FRAME_CLOSE :
# Close control frame,')
if dataLen > 0 :
def onCloseDataRecv(xasCli, data, arg) :
self._close()
self._recvData(onCloseDataRecv, dataLen)
else :
self._close()
else :
# Unknown frame type,
self._close(1002, 'Protocol error (bad opcode)')
# - End of endOfHeader -
def getMaskingKey(dataLen) :
if masked :
# Frame is masked by the next 4 bytes key,
def onMaskingKeyRecv(xasCli, data, arg) :
endOfHeader(dataLen=dataLen, maskingKey=bytes(data))
self._recvData(onMaskingKeyRecv, 4)
else :
# Frame is not masked,
endOfHeader(dataLen=dataLen, maskingKey=None)
# - End of getMaskingKey -
if length == 0 and not isCtrlFrame :
# Bad frame for a no control frame without payload data,
self._close(1002, 'Protocol error (payload data required)')
elif length <= 0x7D :
# Frame length <= 0x7D,
getMaskingKey(dataLen=length)
elif isCtrlFrame :
# Bad frame for length of control frame > 0x7D,
self._close(1002, 'Protocol error (bad control frame length)')
elif length == 0x7E :
# Frame length is encoded on next 16 bits,
def onLenExt1Recv(xasCli, data, arg) :
length = (data[0] << 8) + data[1]
if length < 0x7E :
# Bad frame for 16 bits length < 0x7E,
self._close(1002, 'Protocol error (bad length encoding)')
else :
getMaskingKey(dataLen=length)
self._recvData(onLenExt1Recv, 2)
else :
# Frame length is encoded on next 64 bits.
# It's too large and not implemented,
self._close(1009, 'Frame is too large to be processed')
# - End of onHdrStartingRecv -
self._xasCli.AsyncRecvData( size = 2,
onDataRecv = onHdrStartingRecv,
timeoutSec = self._waitFrameTimeoutSec )
# ------------------------------------------------------------------------
def _sendFrame(self, opcode, data=None, fin=True) :
try :
if opcode >= 0x00 and opcode <= 0x0F :
length = len(data) if data else 0
if length <= 0xFFFF :
data = bytes([ (opcode | 0x80) if fin else opcode ] ) \
+ bytes([ length if length <= 0x7D else 0x7E ] ) \
+ (pack('>H', length) if length >= 0x7E else b'') \
+ (bytes(data) if data else b'')
return self._xasCli.AsyncSendData(data)
except :
pass
return False
# ------------------------------------------------------------------------
def _close(self, statusCode=None, reason=None, waitCloseFrame=False) :
if not self._isClosed :
if statusCode :
data = pack('>H', statusCode)
if reason :
data += reason.encode('UTF-8')
else :
data = None
self._sendFrame(WebSocket._OP_FRAME_CLOSE, data)
self._isClosed = True
if waitCloseFrame :
return
self._xasCli.Close()
# ------------------------------------------------------------------------
def SendTextMessage(self, msg) :
if not isinstance(msg, str) or len(msg) == 0 :
raise ValueError('"msg" must be a not empty string.')
if not self._isClosed :
try :
msg = msg.encode('UTF-8')
except :
return False
return self._sendFrame(WebSocket._OP_FRAME_TEXT, msg)
return False
# ------------------------------------------------------------------------
def SendBinaryMessage(self, msg) :
try :
bytes([msg[0]])
except :
raise ValueError('"msg" must be a not empty bytes object.')
if not self._isClosed :
return self._sendFrame(WebSocket._OP_FRAME_BIN, msg)
return False
# ------------------------------------------------------------------------
def Close(self) :
if not self._isClosed :
self._close(1000, 'Normal closure', waitCloseFrame=True)
# ------------------------------------------------------------------------
@property
def Request(self) :
return self._request
# ------------------------------------------------------------------------
@property
def IsClosed(self) :
return self._isClosed
# ------------------------------------------------------------------------
@property
def WaitFrameTimeoutSec(self) :
return self._waitFrameTimeoutSec
@WaitFrameTimeoutSec.setter
def WaitFrameTimeoutSec(self, value) :
if not isinstance(value, int) or value <= 0 :
raise ValueError('"WaitFrameTimeoutSec" must be a positive integer.')
self._waitFrameTimeoutSec = value
# ------------------------------------------------------------------------
@property
def MaxRecvMessageLength(self) :
return self._maxRecvMsgLen
@MaxRecvMessageLength.setter
def MaxRecvMessageLength(self, value) :
if value is not None and (not isinstance(value, int) or value < 125) :
raise ValueError('"MaxRecvMessageLength" must be an integer >= 125 or None.')
self._maxRecvMsgLen = value
# ------------------------------------------------------------------------
@property
def OnTextMessage(self) :
return self._onTextMsg
@OnTextMessage.setter
def OnTextMessage(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnTextMessage" must be a function.')
self._onTextMsg = value
# ------------------------------------------------------------------------
@property
def OnBinaryMessage(self) :
return self._onBinMsg
@OnBinaryMessage.setter
def OnBinaryMessage(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnBinaryMessage" must be a function.')
self._onBinMsg = value
# ------------------------------------------------------------------------
@property
def OnClosed(self) :
return self._onClosed
@OnClosed.setter
def OnClosed(self, value) :
if type(value) is not type(lambda x:x) :
raise ValueError('"OnClosed" must be a function.')
self._onClosed = value
# ============================================================================
# ============================================================================
# ============================================================================
@@ -0,0 +1,184 @@
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
import re
# ============================================================================
# ===( @WebRoute decorator )==================================================
# ============================================================================
def WebRoute(method=None, routePath=None, name=None) :
if type(method) is type(lambda x:x) and not routePath :
raise ValueError('[@WebRoute] arguments are required for this decorator.')
def decorated(handler) :
RegisterRoute(handler, method, routePath, name)
s = (' (%s)' % name) if name else ''
print(' + [@WebRoute] %s %s' % (method, routePath) + s)
return handler
return decorated
# ============================================================================
# ===( RegisterResult )=======================================================
# ============================================================================
def RegisterRoute(handler, method, routePath, name=None) :
if type(handler) is not type(lambda x:x) :
raise ValueError('"handler" must be a function.')
if not isinstance(method, str) or len(method) == 0 :
raise ValueError('"method" requires a not empty string.')
if not isinstance(routePath, str) or len(routePath) == 0 :
raise ValueError('"routePath" requires a not empty string.')
if routePath[0] != '/' :
raise ValueError('"routePath" must start with a "/".')
if name is not None and not isinstance(name, str) :
raise ValueError('"name" must be a string or None.')
method = method.upper()
if len(routePath) > 1 and routePath.endswith('/') :
routePath = routePath[:-1]
# Route -> '/users/<uID>/addresses/<addrID>/test/<anotherID>'
# Regex -> '/users/(\w*)/addresses/(\w*)/test/(\w*)$'
# Args -> ['uID', 'addrID', 'anotherID']
argNames = [ ]
regex = ''
try :
for i, part in enumerate(routePath.lower().split('/')) :
if i > 0 :
if part.startswith('<') and part.endswith('>') :
argName = part[1:-1]
if not argName :
raise Exception
argNames.append(argName)
regex += '/([\\w.]*)'
else :
regex += '/' + part
regex = re.compile(regex + '$')
except :
raise ValueError('Bad route path: "%s".' % routePath)
for regRoute in _registeredRoutes :
if regRoute.Method == method and regRoute.Regex == regex :
raise ValueError('Duplicated route: "%s".' % routePath)
regRoute = _registeredRoute(handler, method, routePath, name, regex, argNames)
_registeredRoutes.append(regRoute)
# ============================================================================
# ===( ResolveRoute )=========================================================
# ============================================================================
def ResolveRoute(method, path) :
try :
path = path.lower()
if len(path) > 1 and path.endswith('/') :
path = path[:-1]
for regRoute in _registeredRoutes :
if regRoute.Method == method :
reMatch = regRoute.Regex.match(path)
if reMatch :
if not regRoute.ArgNames :
return RouteResult(regRoute)
args = { }
for i, argName in enumerate(regRoute.ArgNames) :
argValue = reMatch.group(i+1)
try :
argValue = int(argValue)
except :
pass
args[argName] = argValue
return RouteResult(regRoute, args)
except :
pass
return None
# ============================================================================
# ===( PathFromRoute )========================================================
# ============================================================================
def PathFromRoute(routeName, routeArgs={ }) :
if not isinstance(routeName, str) or len(routeName) == 0 :
raise ValueError('"routeName" requires a not empty string.')
if not isinstance(routeArgs, dict) :
raise ValueError('"routeArgs" must be a dict.')
for regRoute in _registeredRoutes :
if regRoute.Name == routeName :
path = regRoute.RoutePath
for argName in regRoute.ArgNames :
arg = routeArgs.get(argName, None)
if arg is None :
raise ValueError('"routeArgs" does not contains "%s" for route %s.' % (argName, routeName))
path = path.replace('<%s>' % argName, str(arg))
return path
raise ValueError('"routeName" is not a registered route (%s).' % routeName)
# ============================================================================
# ===( RouteResult )==========================================================
# ============================================================================
class RouteResult :
def __init__(self, regRoute, args=None) :
self._regRoute = regRoute
self._args = args
def __repr__(self) :
if self._regRoute.Name :
return self._regRoute.Name
return '%s %s' % (self._regRoute.Method, self._regRoute.RoutePath)
@property
def Handler(self) :
return self._regRoute.Handler
@property
def Method(self) :
return self._regRoute.Method
@property
def RoutePath(self) :
return self._regRoute.RoutePath
@property
def Name(self) :
return self._regRoute.Name
@property
def Args(self) :
return self._args
# ============================================================================
# ===( Methods )==============================================================
# ============================================================================
GET = 'GET'
HEAD = 'HEAD'
POST = 'POST'
PUT = 'PUT'
DELETE = 'DELETE'
OPTIONS = 'OPTIONS'
PATCH = 'PATCH'
# ============================================================================
# ===( Private registered routes )===========================================
# ============================================================================
_registeredRoutes = [ ]
# ------------------------------------------------------------------------
class _registeredRoute :
def __init__(self, handler, method, routePath, name, regex, argNames) :
self.Handler = handler
self.Method = method
self.RoutePath = routePath
self.Name = name
self.Regex = regex
self.ArgNames = argNames
# ============================================================================
# ============================================================================
# ============================================================================
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDODCCAiACCQCr018O4/g/kzANBgkqhkiG9w0BAQUFADBdMQswCQYDVQQGEwJG
UjEOMAwGA1UEBwwFUEFSSVMxDDAKBgNVBAoMA0hDMjERMA8GA1UEAwwIKi5oYzIu
ZnIxHTAbBgkqhkiG9w0BCQEWDmNvbnRhY3RAaGMyLmZyMCAXDTE4MTIxNjEyMTI0
NFoYDzIyOTIwOTI5MTIxMjQ0WjBdMQswCQYDVQQGEwJGUjEOMAwGA1UEBwwFUEFS
SVMxDDAKBgNVBAoMA0hDMjERMA8GA1UEAwwIKi5oYzIuZnIxHTAbBgkqhkiG9w0B
CQEWDmNvbnRhY3RAaGMyLmZyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
AQEAvj1L4FLuOLypHqERQKkYcGJyIwt0vm/lbl6+hDF0nt3GVmYijorLuUn1tTE2
93cXrixbZ9Bd65c8hsmEvVZbvjG2UmhXxGxk7NserbF4fAyZ+w7k+L0YOO1s5A53
TcqWOLUd7E8J36j+SVx90T3VMnrl655K+ZqWM0IQnmLweddp+y1rZ0gAUhR/wmUB
gWlfCCyhRl9ktAD0q0e6sVq7x/fwYTpG5ENCGPD3ZVlsgMWZMcj8liFbY7YNsVxD
O1+eH6A20X7FwOSpX9AxVoYnDfB0Dlh0/7FaYIZ0ZhDDyvied43WW2DTEkKsdC48
8Yr7GBb1Fw/Go3oYkaMChQN/FQIDAQABMA0GCSqGSIb3DQEBBQUAA4IBAQBW/KlS
gTScaWf1RcpjHvvdBYfBwSlYZg5sxVbV2cPmC+M52EPbzIT5qM6TnTwnJgywj+zx
NzxVvDwDIfLNO8NmKvsVjvzaMgjPoeknoZ33jULfLF8cgwrFzE+XmXUDii9dugQm
GipA0JcWHGnR93pYJoZuXH7ACneNR3MNYIkHJ2M+PkkVppdx8ilOwgTI4pCLGAhm
fwc/Bmkz6HEwju6vRzwdae9Z0xL7wKmZxO2IujbZpgQvwhf0ZvJzpXlmK2dxcBL/
YrwgvneacuXWM3SXPTIlCNgYHzi0Mi+ElUqnfAjI1MtMOpW+jKpZxHRkJqfwFalp
fLavWdBgXaJKb3Tx
-----END CERTIFICATE-----
@@ -0,0 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAvj1L4FLuOLypHqERQKkYcGJyIwt0vm/lbl6+hDF0nt3GVmYi
jorLuUn1tTE293cXrixbZ9Bd65c8hsmEvVZbvjG2UmhXxGxk7NserbF4fAyZ+w7k
+L0YOO1s5A53TcqWOLUd7E8J36j+SVx90T3VMnrl655K+ZqWM0IQnmLweddp+y1r
Z0gAUhR/wmUBgWlfCCyhRl9ktAD0q0e6sVq7x/fwYTpG5ENCGPD3ZVlsgMWZMcj8
liFbY7YNsVxDO1+eH6A20X7FwOSpX9AxVoYnDfB0Dlh0/7FaYIZ0ZhDDyvied43W
W2DTEkKsdC488Yr7GBb1Fw/Go3oYkaMChQN/FQIDAQABAoIBAFZYmAHfYkTaTKCc
VqpUlcUcydViM8DkJOytkCeMEvSwkH9SqEiucr1M9nshNWOo6FSjyXEbQCXYZR6A
hQEzGzz+b1SEC6IZ2M0wv4Hy1U7ooVM0dXT4zu+3w/7XGgty8jAW9Nf3H/ImUBSY
KHs6Z3QcGBOTq1ATfC0TxVs+aQvDk/ceLuEbjDZAyhkqJTcUJaUrai91dwe1ChQj
uBZCRa87Z7gdFBItY+g8RBtdOoT9KZNDZ4OqHXpzzg0la1GMbLKNA82dqUx3mexr
HHlxV+cDt7gFT80Usj9Knk0tQnoiLkxFBblcHId9b93bSKdzFiVAUxkCkbI8xcUX
JVf9a1kCgYEA4NsV5sFye2O+7Idwm1eUu4e/lXBrnwpNmDVy3rYlweQGNSyMrU+A
wcBS7bAghq4QdFbZMEqNVxyFJFa7W1Xvy3HqCpsEUnDO6n9wCN8aCUGMU2YFP9Y/
OoIrTye2ZO36C5pwZiOmT8KZ3Z45f1CxKrgVRDVnfwcCd7xLpPL4BKcCgYEA2JbJ
i8eismhpx4oGvoV1LCgiazgm5+w1b+ZvzaknAAocqwNXLMVNqbGNY/136dCB1DYj
A/Nvyr/WxBBTwYEXOoefgD0BpV2JjBmHckBTtwC8v3Ybi1dLm+JOtFT9uB1hXn/u
08VahTU9GSo8OCyeJF5eDLcg3Rx0ZGtFRYPWieMCgYAN0CemR1f7EIOYEDHwuQ6f
/pTcX02dNYrSwOXPnKzxHkrrVVNHCk1EmcX+aAV3gJXuL6+j8dCA+3WKZ/GWiM70
VokkIaXAUsHDUhTV1q7IxsgSD4BfDZBQzdJPSIdB6ASmVdR10dbTq4a8QI4TridU
En7r88Pp38pdBKo49dwanQKBgHnF9ZVIbfoe6HJO8VHHGUT1X7ymuoEk9jpu9idM
VmgYR1wDKc07NVoWQKeaSARGvegBdBhxk0YMLATaJS0jllrLC+t+4WEHQSFq7RNY
hXjbykNfdUcXkqQXTibnrisJIciO50lbqXRBpZNzgp4Wv+c0w24kvC51JB+djDn0
UPf/AoGBAKZoSsbLjSIrxXDkASEGohLgId7AqJBndzCVzWV2+YQrgJCMMorBFVqC
7myB69IDooBFhR7D0Is3uIUzyk62zeRSQPTgQYjUq1LYtvB+sLA3Dqs8cWdFWpAc
a8lnxGKUNRpO18WIuNbFSibK6jyPqA1iRn/9KhZwRmygNzMh/f9P
-----END RSA PRIVATE KEY-----
+1
View File
@@ -0,0 +1 @@
microwebsrv2.hc2.fr
@@ -0,0 +1 @@
theme: jekyll-theme-hacker
Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

+189
View File
@@ -0,0 +1,189 @@
import sys
sys.path.append('/web_root/microWebServer2/')
from MicroWebSrv2.microWebSrv2 import *
from time import sleep
from _thread import allocate_lock
# ============================================================================
# ============================================================================
# ============================================================================
@WebRoute(GET, '/test-redir')
def RequestTestRedirect(microWebSrv2, request) :
request.Response.ReturnRedirect('/test.pdf')
# ============================================================================
# ============================================================================
# ============================================================================
@WebRoute(GET, '/test-post', name='TestPost1/2')
def RequestTestPost(microWebSrv2, request) :
content = """\
<!DOCTYPE html>
<html>
<head>
<title>POST 1/2</title>
</head>
<body>
<h2>MicroWebSrv2 - POST 1/2</h2>
User address: %s<br />
<form action="/test-post" method="post">
First name: <input type="text" name="firstname"><br />
Last name: <input type="text" name="lastname"><br />
<input type="submit" value="OK">
</form>
</body>
</html>
""" % request.UserAddress[0]
request.Response.ReturnOk(content)
# ------------------------------------------------------------------------
@WebRoute(POST, '/test-post', name='TestPost2/2')
def RequestTestPost(microWebSrv2, request) :
data = request.GetPostedURLEncodedForm()
try :
firstname = data['firstname']
lastname = data['lastname']
except :
request.Response.ReturnBadRequest()
return
content = """\
<!DOCTYPE html>
<html>
<head>
<title>POST 2/2</title>
</head>
<body>
<h2>MicroWebSrv2 - POST 2/2</h2>
Hello %s %s :)<br />
</body>
</html>
""" % ( MicroWebSrv2.HTMLEscape(firstname),
MicroWebSrv2.HTMLEscape(lastname) )
request.Response.ReturnOk(content)
# ============================================================================
# ============================================================================
# ============================================================================
def OnWebSocketAccepted(microWebSrv2, webSocket) :
print('Example WebSocket accepted:')
print(' - User : %s:%s' % webSocket.Request.UserAddress)
print(' - Path : %s' % webSocket.Request.Path)
print(' - Origin : %s' % webSocket.Request.Origin)
if webSocket.Request.Path.lower() == '/wschat' :
WSJoinChat(webSocket)
else :
webSocket.OnTextMessage = OnWebSocketTextMsg
webSocket.OnBinaryMessage = OnWebSocketBinaryMsg
webSocket.OnClosed = OnWebSocketClosed
# ============================================================================
# ============================================================================
# ============================================================================
def OnWebSocketTextMsg(webSocket, msg) :
print('WebSocket text message: %s' % msg)
webSocket.SendTextMessage('Received "%s"' % msg)
# ------------------------------------------------------------------------
def OnWebSocketBinaryMsg(webSocket, msg) :
print('WebSocket binary message: %s' % msg)
# ------------------------------------------------------------------------
def OnWebSocketClosed(webSocket) :
print('WebSocket %s:%s closed' % webSocket.Request.UserAddress)
# ============================================================================
# ============================================================================
# ============================================================================
global _chatWebSockets
_chatWebSockets = [ ]
global _chatLock
_chatLock = allocate_lock()
# ------------------------------------------------------------------------
def WSJoinChat(webSocket) :
webSocket.OnTextMessage = OnWSChatTextMsg
webSocket.OnClosed = OnWSChatClosed
addr = webSocket.Request.UserAddress
with _chatLock :
for ws in _chatWebSockets :
ws.SendTextMessage('<%s:%s HAS JOINED THE CHAT>' % addr)
_chatWebSockets.append(webSocket)
webSocket.SendTextMessage('<WELCOME %s:%s>' % addr)
# ------------------------------------------------------------------------
def OnWSChatTextMsg(webSocket, msg) :
addr = webSocket.Request.UserAddress
with _chatLock :
for ws in _chatWebSockets :
ws.SendTextMessage('<%s:%s> %s' % (addr[0], addr[1], msg))
# ------------------------------------------------------------------------
def OnWSChatClosed(webSocket) :
addr = webSocket.Request.UserAddress
with _chatLock :
if webSocket in _chatWebSockets :
_chatWebSockets.remove(webSocket)
for ws in _chatWebSockets :
ws.SendTextMessage('<%s:%s HAS LEFT THE CHAT>' % addr)
# ============================================================================
# ============================================================================
# ============================================================================
print()
# Loads the PyhtmlTemplate module globally and configure it,
pyhtmlMod = MicroWebSrv2.LoadModule('PyhtmlTemplate')
pyhtmlMod.ShowDebug = True
pyhtmlMod.SetGlobalVar('TestVar', 12345)
# Loads the WebSockets module globally and configure it,
wsMod = MicroWebSrv2.LoadModule('WebSockets')
wsMod.OnWebSocketAccepted = OnWebSocketAccepted
# Instanciates the MicroWebSrv2 class,
mws2 = MicroWebSrv2()
mws2.BindAddress = ('0.0.0.0', 8080) # Binds to all interfaces on port 8080.
# SSL is not correctly supported on MicroPython.
# But you can uncomment the following for standard Python.
# mws2.EnableSSL( certFile = 'SSL-Cert/openhc2.crt',
# keyFile = 'SSL-Cert/openhc2.key' )
# For embedded MicroPython, use a very light configuration,
mws2.SetEmbeddedConfig()
# All pages not found will be redirected to the home '/',
mws2.NotFoundURL = '/'
# Starts the server as easily as possible in managed mode,
mws2.StartManaged()
# Main program loop until keyboard interrupt,
try :
while mws2.IsRunning :
sleep(1)
except KeyboardInterrupt :
pass
# End,
print()
mws2.Stop()
print('Bye')
print()
# ============================================================================
# ============================================================================
# ============================================================================
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md'), encoding='utf-8').read()
setup(
name='MicroWebSrv2',
version='2.0.6',
description='Embedded webserver for MicroPython and CPython',
long_description=README,
author='Jean-Christophe Bos',
author_email='jczic.bos@gmail.com',
url='https://github.com/jczic/MicroWebSrv2',
download_url='https://github.com/jczic/MicroWebSrv2/archive/master.zip',
packages=find_packages(),
classifiers=[
'Environment :: Web Environment',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Embedded Systems',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: MicroPython',
'License :: OSI Approved :: MIT License',
'Development Status :: 5 - Production/Stable',
],
)
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

+43
View File
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang=fr>
<head>
<meta charset="UTF-8" />
<title>MicroWebSrv2</title>
<link rel="stylesheet" href="style.css" />
</head>
<body style="padding: 0 70px;">
<h1>&lt; MicroWebSrv2 /&gt;</h1>
<h2>About</h2>
<p>
This project follows the embedded <a href="https://github.com/jczic/MicroWebSrv">MicroWebSrv</a>,
which is mainly used on microcontrollers such as Pycom, ESP32 and STM32 on Pyboards.<br />
<br />
In a need for scalability and to meet the IoT universe, <b>microWebSrv2</b> was developed as a new project
and has been completely redesigned to be much more robust and efficient that its predecessor.<br />
<br />
Internal mechanisms works <b>directly at I/O level</b>, are fully asynchronous from end to end, and manages the memory in a highly optimized way.
Also, architecture makes its integration very easy and the source code, <b>MIT licensed</b>, remains really small.<br />
<br />
</p>
<ul>
<li><a href="test-redir">Test a redirection</a></li>
<li><a href="test-post">Test a POST form</a></li>
<li><a href="wstest.html">Test the WebSockets page</a></li>
<li><a href="wschat.html">Test the multi-users chat page</a></li>
<li><a href="test.pyhtml">Test a pyhtml template page</a></li>
</ul>
<br />
<hr />
<br />
<div style="text-align: center">
<img src="pdf.png" />
<p>
View a « <a href="test.pdf">PDF file</a> »
</p>
</div>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

+44
View File
@@ -0,0 +1,44 @@
html, body {
margin: 0;
padding: 0;
}
body {
margin: 30px;
background-color: white;
font-family: "Trebuchet MS", Verdana, sans-serif;
letter-spacing: 2px;
}
h1 {
color: #D35F8D;
text-align: center;
}
h2 {
color: #5FA3D3;
padding-left: 15px;
}
p, ul, li, td {
color: black;
}
a:link {
color: green;
text-decoration: underline;
}
a:visited {
color: gray;
}
a:hover {
color: red;
text-decoration: none;
}
a:active, a:focus {
color: red;
}
.sep {
margin: 15px 0;
height: 3px;
background-color: #5FA3D3;
}
.label {
color: #D35F8D;
font-weight: bold;
}
Binary file not shown.
+133
View File
@@ -0,0 +1,133 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>MicroWebSrv2 - PyhtmlTemplate Module</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
{{ py }}
import sys
global Toto
try :
Toto += 1
except :
Toto = 1
{{ end }}
<h1>MicroWebSrv2 - PyhtmlTemplate Module</h1>
<div class="sep"></div>
Platform: {{ sys.platform }} <br />
Version: {{ sys.version }} <br />
<div class="sep"></div>
Global var "TestVar" : <span class="label">{{ TestVar }}</span><br />
* Set from the main program.
<div class="sep"></div>
Global var "Toto" : <span class="label">{{ Toto }}</span><br />
* Refresh this page to see this variable changing.
<div class="sep"></div>
{{ py }}
print('Unescaped HTML: <strong><u>Okay</u></strong>')
{{ end }}
<div class="sep"></div>
Your address:<br />
<ul>
<li> IP = {{ Request.UserAddress[0] }} </li>
<li> Port = {{ Request.UserAddress[1] }} </li>
</ul>
<div class="sep"></div>
{{ if 'CHROME' in Request.UserAgent.upper() }}
You are on <span class="label">Chrome</span> browser.
{{ elif 'FIREFOX' in Request.UserAgent.upper() }}
You are on <span class="label">Firefox</span> browser.
{{ else }}
You are not on Chrome or Firefox browser.
{{ end }}
<div class="sep"></div>
You are in SSL: {{ Request.IsSSL }}<br />
<div class="sep"></div>
Your host: {{ Request.Host }}<br />
<div class="sep"></div>
Requested path: {{ Request.Path }}<br />
<div class="sep"></div>
Your query params:
{{ if not Request.QueryParams }}
<a href="?question=How are you?&answer=I'm fine!">
Test query string on this page.
</a>
{{ else }}
<ul>
{{ for param in Request.QueryParams }}
<li>Param "{{ param }}" = "{{ Request.QueryParams[param] }}"</li>
{{ end }}
</ul>
{{ end }}
<div class="sep"></div>
Accepted content types:
<ul>
{{ for accept in Request.Accept }}
<li>{{ accept }}</li>
{{ end }}
</ul>
<div class="sep"></div>
Accepted encodings:
<ul>
{{ for encoding in Request.AcceptEncodings }}
<li>{{ encoding }}</li>
{{ end }}
</ul>
<div class="sep"></div>
Accepted languages:
<ul>
{{ for language in Request.AcceptLanguages }}
<li>{{ language }}</li>
{{ end }}
</ul>
<div class="sep"></div>
Your request is keep-alive: {{ Request.IsKeepAlive }}<br />
<div class="sep"></div>
Your user agent:<br />
{{ Request.UserAgent }}
<div class="sep"></div>
</body>
</html>
+124
View File
@@ -0,0 +1,124 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>MicroWebSrv2 - WS Chat</title>
<link rel="stylesheet" href="style.css" />
</head>
<style>
.chat-zone {
height : 350px;
padding: 10px;
background-color: #304050;
font: 15px monospace;
color: white;
overflow: scroll;
}
#input-chat {
height: 40px;
border: 0px;
padding: 0px 10px;
outline: none;
border-top: 1px solid white;
background-color: #304050;
font: 15px monospace;
letter-spacing: 2px;
color: white;
}
input {
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
width: 100%;
margin-top: 3px;
border: 2px solid #5FA3D3;
}
</style>
<script language="javascript">
function init()
{
var scheme
if (window.location.protocol == 'https:')
scheme = 'wss:';
else
scheme = 'ws:';
var wsUri = scheme + '//' + window.location.hostname + '/wschat';
writeLineToChat("Connection to " + wsUri + "...")
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen (evt) };
websocket.onclose = function(evt) { onClose (evt) };
websocket.onmessage = function(evt) { onMessage (evt) };
websocket.onerror = function(evt) { onError (evt) };
getElmById("input-chat").addEventListener("keyup", onChatLine);
getElmById("input-chat").focus()
}
function getElmById(id) {
return document.getElementById(id);
}
function writeLineToChat(line)
{
var elm = getElmById('chat');
if (elm)
{
var lineElm = document.createElement('div');
if (line) {
var time = new Date().toLocaleTimeString();
lineElm.innerText = "[" + time + "] " + line;
}
else
lineElm.innerHTML = '&nbsp;';
elm.appendChild(lineElm);
elm.scrollTop = elm.scrollHeight;
}
}
function onOpen(evt)
{
writeLineToChat("[CONNECTED]")
}
function onClose(evt)
{
writeLineToChat("[CONNECTION CLOSED]")
}
function onMessage(evt)
{
writeLineToChat(evt.data)
}
function onError(evt)
{
writeLineToChat("[CONNECTION ERROR]")
}
function onChatLine(e) {
key = (e.key || e.keyCode);
if (key === 13 || key.toUpperCase() === "ENTER") {
input = getElmById("input-chat");
line = input.value.trim();
input.value = "";
if (line.length > 0)
websocket.send(line);
}
}
window.addEventListener("load", init, false);
</script>
<body>
<h1>MicroWebSrv2 - WS Chat</h1>
<div id="chat" class="chat-zone">
</div>
<input id="input-chat" type="text" />
</body>
</html>
+92
View File
@@ -0,0 +1,92 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>MicroWebSrv2 - WebSockets Module</title>
<link rel="stylesheet" href="style.css" />
</head>
<script language="javascript">
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket()
{
var scheme, defaultPort
if (window.location.protocol == 'https:')
{
scheme = 'wss:';
defaultPort = 443;
}
else
{
scheme = 'ws:';
defaultPort = 80;
}
var wsUri = scheme + '//' + window.location.hostname;
if (window.location.port !== defaultPort)
wsUri += ':' + window.location.port;
writeToScreen("Connecting to " + wsUri + "...")
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen (evt) };
websocket.onclose = function(evt) { onClose (evt) };
websocket.onmessage = function(evt) { onMessage (evt) };
websocket.onerror = function(evt) { onError (evt) };
}
function onOpen(evt)
{
writeToScreen("<strong>-- CONNECTED --</strong>");
SendMsg("Hello world :)");
SendMsg("This is a WebSocket test");
SendMsg("(with a text frame encoded in UTF-8)");
setTimeout( function() { websocket.close() }, 3000 )
}
function onClose(evt)
{
writeToScreen("<strong>-- DISCONNECTED --</strong>");
}
function onMessage(evt)
{
writeToScreen('MSG FROM SERVER : <span style="color: blue;">' + evt.data + '</span>');
}
function onError(evt)
{
writeToScreen('ERROR : <span style="color: red;">' + evt.data + '</span>');
}
function SendMsg(msg)
{
writeToScreen('MSG TO SERVER : <span style="color: green;">' + msg + '</span>');
websocket.send(msg);
}
function writeToScreen(s)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = s;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<body>
<h1>MicroWebSrv2 - WebSockets Module</h1>
<div id="output"></div>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
.cm-s-monokai.CodeMirror{background:#272822;color:#f8f8f2}.cm-s-monokai div.CodeMirror-selected{background:#49483e}.cm-s-monokai .CodeMirror-line::selection,.cm-s-monokai .CodeMirror-line>span::selection,.cm-s-monokai .CodeMirror-line>span>span::selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-line::-moz-selection,.cm-s-monokai .CodeMirror-line>span::-moz-selection,.cm-s-monokai .CodeMirror-line>span>span::-moz-selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-gutters{background:#272822;border-right:0}.cm-s-monokai .CodeMirror-guttermarker{color:#fff}.cm-s-monokai .CodeMirror-guttermarker-subtle{color:#d0d0d0}.cm-s-monokai .CodeMirror-linenumber{color:#d0d0d0}.cm-s-monokai .CodeMirror-cursor{border-left:1px solid #f8f8f0}.cm-s-monokai span.cm-comment{color:#75715e}.cm-s-monokai span.cm-atom{color:#ae81ff}.cm-s-monokai span.cm-number{color:#ae81ff}.cm-s-monokai span.cm-comment.cm-attribute{color:#97b757}.cm-s-monokai span.cm-comment.cm-def{color:#bc9262}.cm-s-monokai span.cm-comment.cm-tag{color:#bc6283}.cm-s-monokai span.cm-comment.cm-type{color:#5998a6}.cm-s-monokai span.cm-attribute,.cm-s-monokai span.cm-property{color:#a6e22e}.cm-s-monokai span.cm-keyword{color:#f92672}.cm-s-monokai span.cm-builtin{color:#66d9ef}.cm-s-monokai span.cm-string{color:#e6db74}.cm-s-monokai span.cm-variable{color:#f8f8f2}.cm-s-monokai span.cm-variable-2{color:#9effff}.cm-s-monokai span.cm-type,.cm-s-monokai span.cm-variable-3{color:#66d9ef}.cm-s-monokai span.cm-def{color:#fd971f}.cm-s-monokai span.cm-bracket{color:#f8f8f2}.cm-s-monokai span.cm-tag{color:#f92672}.cm-s-monokai span.cm-header{color:#ae81ff}.cm-s-monokai span.cm-link{color:#ae81ff}.cm-s-monokai span.cm-error{background:#f92672;color:#f8f8f0}.cm-s-monokai .CodeMirror-activeline-background{background:#373831}.cm-s-monokai .CodeMirror-matchingbracket{text-decoration:underline;color:#fff!important}
+85
View File
@@ -0,0 +1,85 @@
.card {
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
margin-bottom: 20px;
}
.card-header {
background-color: #f8f9fa;
font-weight: bold;
}
.form-control {
font-size: 1.1em;
}
#feedbackVoltage,
#feedbackCurrent,
#filamentVoltage,
#filamentCurrent {
background-color: #f8f9fa;
font-weight: bold;
color: #0d6efd;
}
.btn-primary {
width: 100%;
margin-top: 10px;
}
/* 导航栏样式 */
.navbar {
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.navbar-brand {
font-weight: bold;
}
.nav-link {
font-size: 1.1em;
}
.nav-link i {
margin-right: 5px;
}
/* 编辑器相关样式 */
.CodeMirror {
height: calc(100vh - 200px);
border: 1px solid #ddd;
border-radius: 4px;
}
#fileTree {
height: calc(100vh - 200px);
overflow-y: auto;
}
.jstree-default .jstree-icon {
color: #0d6efd;
}
.jstree-default .jstree-themeicon {
color: #6c757d;
}
.jstree-default .jstree-themeicon-custom {
color: #0d6efd;
}
/* 文件类型图标颜色 */
.bi-filetype-py {
color: #306998;
}
.bi-filetype-json {
color: #f7df1e;
}
.bi-filetype-sh {
color: #4eaa25;
}
.bi-folder {
color: #ffc107;
}
File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More