前一段时间给IP摄像头和USB摄像头加入RTMP推流支持,支持将音视频推送到直播平台做直播。甚至YouTube也能推过去,前提是你要有个好梯子😀就能实现上图的效果,网络状况好的时候好不错,延迟10秒以上。如果是自己搭推流服务器(像nginx-rtmp或者srs)或者使用国内直播云延迟可以控制到1~2秒以内,使用Flash播放器甚至可以降低到1秒。

实现这个的目的是想直播FPV,即通过采集卡把图传接收的画面通过USB摄像头App显示在手机上的同时推送到直播平台😀苦于搬了房子附近没场子飞四轴,就没直播FPV改为家庭监控用了,自己架一个RTMP推流服务器,把旧手机放家里,运行IP摄像头App进行推流,即使家里没有公网IP也能查看家里情况。

IP摄像头和USB摄像头app共用RTMP推流的代码,视频使用H.264编码,音频使用AAC编码,支持根据网络状况自动调整码率,网络状况差时会自动丢帧,以保证延迟。当遇到网络切换或者连接暂时中断时,会自行重连,直到重新连接到推流服务器或者用户自行断开连接。该推流算法自行实现,经过二月份户外4G网络测试效果不错(消耗了近2G流量,刚好二月份移动送流量),即使在户外也能通过4G网络使用IP摄像头或者USB摄像头进行RTMP推流直播。

++++++++++++++++++++++++++++++



前段时间在调试IP摄像头时偶然发现铁通也能刷出独立IP,是183开头的,一开始以为只有铁通网络能够访问,后面发现跟myexternalip.com检测的IP一致,然后IP摄像头居然可以外网访问了,于是写了个python脚本来刷独立IP。

原理很简单,每次路由器重新拨号就能改变IP,然后将路由器的IP跟myexternalip.com检测的外网IP比较,如果一致就是独立IP

我家路由器是水星MD898n(固件:V2.0_140216标准版,以下都是针对此固件,不同版本固件可能不一样),根据Chrome抓包得到每次点击 断线,都会向路由器提交 “[ACT_PPP_DISCONN#2,1,1,0,0,0#0,0,0,0,0,0]0,0\r\n”的指令,点击 连接则提交“[ACT_PPP_CONN#2,1,1,0,0,0#0,0,0,0,0,0]0,0\r\n”,这样就实现路由器重新拨号。路由器登录验证则是base验证,只不过不需要用户名而已。

路由器的IP则可以通过UPnP的方式得到,具体可以参考关于UPnP端口映射的文献。

upnp.py的实现,主要实现get_external_ip()这个函数用于获取路由器IP

import socket
import socket
import re
import urllib2
import httplib
import struct
import time
from xml.dom.minidom import parseString
from urlparse import urlparse
 
xmlLocation = ""
xmlString = ""
 
def _get_external_ip():
	global xmlLocation
	global xmlString
 
	if xmlLocation == "" or xmlString == "":
		ssdpRequest = "M-SEARCH * HTTP/1.1\r\n" + \
						"MX: 3\r\n" + \
						"HOST: 239.255.255.250:1900\r\n" + \
						"MAN: \"ssdp:discover\"\r\n" + \
						"ST: urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\n\r\n"
 
		SSDP_ADDR = "239.255.255.250"
		SSDP_PORT = 1900
 
		sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		sock.bind(('192.168.1.5', 0))
		sock.settimeout(10)
		sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		sock.sendto(ssdpRequest, (SSDP_ADDR, SSDP_PORT))
		resp = sock.recv(1024)
 
		lines = resp.splitlines()
		for line in lines:
			params = line.split(':', 1)
			if len(params) == 2 and params[0].strip().lower() == "location":
				xmlLocation = params[1].strip()
				break
		opened = urllib2.urlopen(xmlLocation)
		xmlString = opened.read()
		opened.close()
 
	GetExternalIPAddress = "<?xml version=\"1.0\"?>" + \
								"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + \
								"<s:Body>" + \
								"<u:GetExternalIPAddress xmlns:u=\"urn:schemas-upnp-org:service:{0}:1\">" + \
								"</u:GetExternalIPAddress>" + \
								"</s:Body>" + \
								"</s:Envelope>"
 
	router_path = urlparse(xmlLocation)
	dom = parseString(xmlString)
 
	service_types = dom.getElementsByTagName('serviceType')
 
	path = ""
	action = ""
	for service in service_types:
		if service.childNodes[0].data.find('WANIPConnection') > 0:
			path = service.parentNode.getElementsByTagName('controlURL')[0].childNodes[0].data
			action = "urn:schemas-upnp-org:service:WANIPConnection:1#GetExternalIPAddress"
		elif service.childNodes[0].data.find('WANPPPConnection') > 0:
			path = service.parentNode.getElementsByTagName('controlURL')[0].childNodes[0].data
			action = "urn:schemas-upnp-org:service:WANPPPConnection:1#GetExternalIPAddress"
		else:
			continue
 
		conn = httplib.HTTPConnection(router_path.hostname, router_path.port)
		conn.request('POST',
			path,
			GetExternalIPAddress,
			{'SOAPAction': action,
			'Content-Type': 'text/xml; charset="utf-8"'}
		)
		resp = conn.getresponse()
		result = resp.read()
		resp.close()
		conn.close()
		dom = parseString(result)
		external_ip = dom.getElementsByTagName('NewExternalIPAddress')[0].childNodes[0].nodeValue
		if external_ip != "0.0.0.0":
			return external_ip
	return ""
 
def get_external_ip():
	while(1):
		try:
			ip = _get_external_ip()
			if ip != "":
				return ip
		except Exception, e:
			print e
		time.sleep(3)
print get_external_ip()

get_global_ip.py的实现

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import httplib
import urllib
import base64
import time
import re,urllib2
import traceback
import upnp
 
def Get_public_ip(): #获取真实的广域网IP
	try:
		opener = urllib2.urlopen("http://myexternalip.com/raw")
		str = opener.read().strip()
		return str
	except Exception,ex:
		print Exception,":",ex
		return None
 
def _sendhttp(data):
	conn = httplib.HTTPConnection('192.168.1.1') #注意路由器的IP,下同
	conn.putrequest('POST', '/cgi?7')
	conn.putheader("Accept", "*/*")
	conn.putheader("Origin", "http://192.168.1.1")
	conn.putheader("Referer", "http://192.168.1.1/")
	conn.putheader("Content-Type", "text/plain")
	conn.putheader("Content-Length", str(len(data)))
	conn.putheader("Cookie", "Authorization=Basic " + base64.b64encode("123456")) # 123456为路由器登录密码
	conn.endheaders()
	conn.send(data)
 
	return conn.getresponse()
def sendhttp(data):
	httpres = _sendhttp(data)
	while httpres.status != 200:
		print httpres.status
		time.sleep(2)
		httpres = _sendhttp(data)
 
	print httpres.status
	print httpres.reason
	print httpres.read()
 
if __name__ == '__main__':
	try:
		print "Global IP:" + Get_public_ip()
		print "Router IP:" + upnp.get_external_ip()
		print "Refreshing..."
		while(1):
			sendhttp("[ACT_PPP_DISCONN#2,1,1,0,0,0#0,0,0,0,0,0]0,0\r\n") #路由器断线
			time.sleep(2)
			sendhttp("[ACT_PPP_CONN#2,1,1,0,0,0#0,0,0,0,0,0]0,0\r\n") #路由器连接,完成一次重新拨号
			time.sleep(1)
			public_ip = Get_public_ip() #获取实际外网IP
			external_ip = upnp.get_external_ip() #获取路由器IP
			if(public_ip == external_ip): #比较
				print "Global IP:" + public_ip
				print "Refresh OK!"
				break
			else:
				print "Router IP:" + external_ip
				print "Global IP:" + public_ip
				print "Continue refreshing..." #不是独立IP,继续刷
		time.sleep(1000)
	except Exception, e:
		print e
		print traceback.format_exc()
		time.sleep(1000)

将两个文件放置同一个目录,运行get_global_ip.py即可,确保跟路由器处于同一子网,并且路由器没有上级路由器,路由器要开启UPnP,切记!不同的路由器只要改一下拨号部分的代码即可。

当然还有粗暴的方式,把这代码弄到树莓派,再让树莓派控制继电器开关路由器电源,路由器每重启一次就能拨号一次,只是过于粗暴体验不佳……😂😂😂😂

本文地址 http://www.shenyaocn.com/2016/09/using_python_obtain_cmcc_global_ip/

昨晚一个朋友把笔记本带过来了,说会自动关机。开机一看,发现散热器出风口没有风,然后机器就自动断电掉了,凭感觉,肯定散热器堵了。拆开散热器一看,如下图所示,正在吃饭的就别看了……

厚厚的灰尘堵住了散热鳍片

把那层像毛毯一样的灰去除之后,重新装上,散热孔出热风了,笔记本运行几个小时都没问题!

本代码用于远程重启水星无线路由一体机MD898N,硬件版本v2,固件版本0.8.0 1.0 v1003.0 Build 140216。

由于需要,需要用C#实现对这台机器的定时重启,根据chrome开发者工具的抓包结果,发现新版的固件不支持直接的base认证,但是原理一样,只是把用base64加密过的密码存在cookies中了(今年开始更新后的固件都是这种登录方式),发送http请求时候带上这个cookies即可通过认证!

具体代码如下:

	string passwd = "12345678";   // 路由器登录密码
	string routeIP = "192.168.1.1";  // 路由器IP
	byte[] bytes = Encoding.Default.GetBytes(passwd);
	string base64str = Convert.ToBase64String(bytes);
 
	string url = "http://" + ip + "/cgi?7";
	HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
	req.Referer = "http://" + ip + "/";
	req.Method = "POST";
	req.CookieContainer = new CookieContainer();
	req.CookieContainer.Add(new Uri(url), new Cookie("Authorization", "Basic " + base64str));
	req.ContentType = "text/plain";
	string payload = "[ACT_REBOOT#0,0,0,0,0,0#0,0,0,0,0,0]0,0\r\n";  // 抓包后发现在请求中携带这个字符串即可让路由器重启
	byte[] pl = Encoding.UTF8.GetBytes(payload);
	req.ContentLength = pl.Length;
	Stream s = req.GetRequestStream();
	s.Write(pl, 0, pl.Length);
	s.Close();
	req.GetResponse();

在编写IP摄像头的Win8.1版和WP8版时遇到多线程调用StreamSocket发送数据时被意外Dispose,具体是StreamSocket是从StreamSocketListener接受连接后传过来的,然后用DataWriter发送一行数据后插入List供别的线程发送数据,问题就出现在别的线程发送数据时产生Dispose异常,可是奇怪的是我并没有将StreamSocket给Dispose,因为我还要用来传输数据呢!

问题解决:在插入List之前,将DataWriter先DetachStream,然后再给别的线程条用,这样就正常了!估计是DataWriter离开作用域后被销毁时顺便把StreamSocket给连带Dispose了,这个在使用StreamSocket时候得注意一下!当然如果用用DataReader的话也得DetachStream!